我的目标是遍历一个数组,取数组中每个元素的值作为key 并播放与该值关联的声音片段。最终想要的结果是依次 按照数组中键的顺序播放声音片段。
这是我到目前为止尝试过的:
//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
都无法阻止
在音频文件完成之前进行迭代。该项目将增加数组的长度和顺序,所以我需要
一些方法来控制数组的每个成员的执行。
有人可以提供任何建议吗?谢谢。
最佳答案
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);
}
关于javascript - 遍历 HTML5 音频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43927319/