我使用下面的代码预加载一个音频文件数组(在用户与启动该过程的按钮交互后)。在所有音频文件触发“canplaythrough”后,代码继续执行:
var loaded = 0;
function loadedAudio() {
// this will be called every time an audio file is loaded
// we keep track of the loaded files vs the requested files
loaded++;
console.log(loaded + " audio files loaded!");
if (loaded == audioFiles.length){
// all have loaded
main();
}
}
function preloadsounds()
{
$("#loader").show();
console.log(level.config);
audioFiles = level.config.soundfiles;
// we start preloading all the audio files with html audio
for (var i in audioFiles) {
preloadAudio(audioFiles[i]);
}
}
function preloadAudio(url)
{
console.log("trying to preload "+ url);
var audio = new Audio();
// once this file loads, it will call loadedAudio()
// the file will be kept by the browser as cache
audio.addEventListener('canplaythrough', loadedAudio, false);
audio.addEventListener('error', function failed(e)
{
console.log("COULD NOT LOAD AUDIO");
$("#NETWORKERROR").show();
});
audio.src = url;
}
在Android(Chrome和Firefox)上工作得很好但是没有一个canplaythrough事件在iOs Safari上被激活(在5s上测试并且模拟X都是11.x)。所有文件都来自同一个Origin。我的日志中也没有收到任何错误消息。
我错过了什么?
(以上代码的基础我来自:https://stackoverflow.com/a/31351186/2602592)
设置load()
后尝试调用src
方法。
function preloadAudio(url)
{
console.log("trying to preload "+ url);
var audio = new Audio();
// once this file loads, it will call loadedAudio()
// the file will be kept by the browser as cache
audio.addEventListener('canplaythrough', loadedAudio, false);
audio.addEventListener('error', function failed(e)
{
console.log("COULD NOT LOAD AUDIO");
$("#NETWORKERROR").show();
});
audio.src = url;
audio.load(); // add this line
}
你检查过网络/服务器并确认Safari正在下载音频文件吗?
如果Safari不下载音频(或仅加载元数据而不是整个文件),您可以在设置audio.preload = 'auto'
之前尝试设置audio.src
我看到许多声称使音频对象工作,尤其是在Safari上!
要快点,我可以告诉你,你不需要太多,只知道在Safari 5及更多版本以及所有浏览器上运行所有内容。
ObjectAudio.src = file;
ObjectAudio.addEventListener ('canplaythrough', Function, false);
ObjectAudio.addEventListener ('progress', Function, false);
ObjectAudio.addEventListener ('timeupdate', Function, false);
当我看到你在做什么时,你不需要复杂的东西。