迭代HTML5音频文件

时间:2017-05-11 23:52:08

标签: javascript arrays html5 audio

我的目标是遍历数组,将数组中每个元素的值作为键 并播放与该值相关联的声音片段。期望的最终结果是顺序的 按照阵列中键的顺序播放声音片段。

这是我到目前为止所尝试的内容:

//there are addresses associated with the color sound values 

function playSound(soundValue){
  $sound.src = soundValue;
  $sound.load();
  $sound.play();
}

function playGame(){
  simonSays = [0,1,2,3];

  var soundOptions = {
    0: yellowSound,
    1: redSound,
    2: blueSound,
    3: greenSound 
  };

  for (var i = 0; i < simonSays.length; i++){
    var callSound = soundOptions[simonSays[i]];
    setTimeout(playSound(callSound),1000 );
  }
};

此代码遍历序列并等待setTimeout个持续时间 完。我收到此错误:

 Uncaught (in promise) DOMException: The play() request was interrupted by a new load request.
    playSound @ logic.js:72
    playGame @ logic.js:120
    onclick @ index.html:37

我的理解是音频文件相互干扰并产生 错误,但另外通过允许的序列的迭代没有延迟 每个文件都要完成。我看了these examples  延迟媒体执行的其他努力 但是,$sound.ended$sound.onended的来电都无法阻止 在音频文件完成之前迭代。该项目将增加阵列的长度和顺序,所以我需要 某种方式来控制数组中每个成员的执行。

有人可以提供任何建议吗?谢谢。

1 个答案:

答案 0 :(得分:1)

setTimeout不会延迟循环。该循环使每个音频文件仅延迟一秒钟。解决方案是将循环放入一个函数中,如下所示:

simonSays = [0,1,2,3];

var soundOptions = {
  0: yellowSound,
  1: redSound,
  2: blueSound,
  3: greenSound 
};

function playGame(){
  startPlaying(0,simonSays.length);
};

function startPlaying(i,l) {
  if (i==l) return;
  var callSound = soundOptions[simonSays[i]];
  playSound(callSound);
  setTimeout("startPlaying("+(i+1)+","+l+")",1000);      
}