js/html5 audio:为什么在iOS Safari上没有触发canplaythrough?

gau*_*lla 6 javascript html5 html5-audio

我使用下面的代码预加载一个音频文件数组(在用户与启动该过程的按钮交互后).在所有音频文件触发"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;
}
Run Code Online (Sandbox Code Playgroud)

在Android(Chrome和Firefox)上工作得很好但是没有一个canplaythrough事件在iOs Safari上被激活(在5s上测试并且模拟X都是11.x).所有文件都来自同一个Origin.我的日志中也没有收到任何错误消息.

我错过了什么?

(以上代码的基础我来自:https://stackoverflow.com/a/31351186/2602592)

Gab*_*oli 12

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
}
Run Code Online (Sandbox Code Playgroud)