这是我到目前为止所拥有的。它创建一个1-4之间的随机数组。但不是按顺序播放音频。它会立即播放所有4种声音。如果我更改audio
变量以在for
循环的每次运行中播放单个声音,它只会播放一次声音。
如何为阵列中的每个项目播放声音?或者你能告诉我我的错误吗?
var level = 5
var myArray = [];
for (var i = 1; i < level; i++) {
myArray.push(getRandomInt(1,4));
}
for (var i = 0; i < myArray.length; i++) {
var audio = new Audio( 'sounds/' + myArray[i] + '.wav');
audio.play();
}
**更新**
所以我已经想出了如何依次播放它们。但我无法弄清楚如何根据数组中的数字播放声音。
var level = 5
var myArray = [];
for (var i = 1; i < level; i++) {
myArray.push(getRandomInt(1,4));
}
var audio0 = new Audio( 'sounds/blank.wav');
var audio1 = new Audio( 'sounds/1.wav');
var audio2 = new Audio( 'sounds/2.wav');
var audio3 = new Audio( 'sounds/3.wav');
var audio4 = new Audio( 'sounds/4.wav');
audio0.play();
audio0.addEventListener('ended', function(){ audio1.play();} )
audio1.addEventListener('ended', function(){ audio2.play();} )
audio2.addEventListener('ended', function(){ audio3.play();} )
audio3.addEventListener('ended', function(){ audio4.play();} )
答案 0 :(得分:0)
尝试使用setTimeout而不是for循环:
var i = 0;
var audio = new Audio( 'sounds/' + myArray[i] + '.wav');
var timeout = setTimeout(function() {
audio.play();
if( ++i < myArray.length ) {
// after playing, reset audio and immediately return
// to prevent the timeout from clearing.
audio = new Audio( 'sounds/' + myArray[i] + '.wav');
return;
}
// clear the timeout when you run out of clips to play.
clearTimeout(timeout);
// audio.duration is in seconds, so multiply by 1000 to get the
// duration in milliseconds
}, audio.duration * 1000);