在Javascript中使用Web Audio API的本地文件 [英] Using local file for Web Audio API in Javascript

查看:101
本文介绍了在Javascript中使用Web Audio API的本地文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Web Audio API在我的iPhone游戏上正常工作。问题是这个应用程序完全是客户端。我想将我的mp3存储在本地文件夹中(并且不需要用户输入驱动),因此我无法使用XMLHttpRequest读取数据。我正在研究使用FileSystem,但Safari不支持它。



是否有其他选择?

编辑:感谢下面的回复。不幸的是,音频API的游戏速度非常缓慢。我有这个工作,延迟只是使用户体验无法接受。澄清一下,我需要的是类似 -

  var request = new XMLHttpRequest(); 
request.open('GET','file:/// ./../sounds/beep-1.mp3',true);
request.responseType ='arraybuffer';
request.onload = function(){
context.decodeAudioData(request.response,function(buffer){
dogBarkingBuffer = buffer;
},onError);
}
request.send();

但这给了我错误 -



XMLHttpRequest无法加载file:///sounds/beep-1.mp3。只有HTTP支持跨源请求。
未捕获错误:NETWORK_ERR:XMLHttpRequest异常101



我理解读取本地文件的安全风险,但肯定在您自己的域中应该没问题?

解决方案

我遇到同样的问题,我发现这个非常简单的解决方案。 div class =snippetdata-lang =jsdata-hide =falsedata-console =truedata-babel =false>

  audio_file.onchange = function(){var files = this.files; var file = URL.createObjectURL(files [0]); audio_player.src = file; audio_player.play();};  

< input id =audio_filetype =fileaccept =audio / */>< audio id =audio_player/>

您可以在这里测试:
http ://jsfiddle.net/Tv8Cm/


I'm trying to get sound working on my iPhone game using the Web Audio API. The problem is that this app is entirely client side. I want to store my mp3s in a local folder (and without being user input driven) so I can't use XMLHttpRequest to read the data. I was looking into using FileSystem but Safari doesn't support it.

Is there any alternative?

Edit: Thanks for the below responses. Unfortunately the Audio API is horribly slow for games. I had this working and the latency just makes the user experience unacceptable. To clarify, what I need is sounething like -

var request = new XMLHttpRequest();
request.open('GET', 'file:///./../sounds/beep-1.mp3', true);
request.responseType = 'arraybuffer';
request.onload = function() {
    context.decodeAudioData(request.response, function(buffer) {
    dogBarkingBuffer = buffer;
}, onError);
}
request.send();

But this gives me the errors -

XMLHttpRequest cannot load file:///sounds/beep-1.mp3. Cross origin requests are only supported for HTTP. Uncaught Error: NETWORK_ERR: XMLHttpRequest Exception 101

I understand the security risks with reading local files but surely within your own domain should be ok?

解决方案

I had the same problem and I found this very simple solution.

audio_file.onchange = function(){
  var files = this.files;
  var file = URL.createObjectURL(files[0]); 
              audio_player.src = file; 
  audio_player.play();
};

<input id="audio_file" type="file" accept="audio/*" />
<audio id="audio_player" />

You can test here: http://jsfiddle.net/Tv8Cm/

这篇关于在Javascript中使用Web Audio API的本地文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆