這個怎麼樣?
var sounds = [];
function playRandom() {
// play a random member of sounds
sounds[Math.floor(Math.random() * sounds.length) + 1].play();
}
// load all the sounds ahead of time
var numberOfSounds = 3;
for (var i = 0; i < numberOfSounds; i++) {
sounds.push(new Howl({
src: ['audio/' + i + '.wav'],
autoplay: false,
loop: false,
volume: 1.0,
onend: function() {
// when one sound ends, play a new random one
playRandom();
},
}));
}
// kick things off with the first random sound
playRandom();
UPDATE
回答下面的評論,這裏的發揮每個重複聲音四次移動到下一個隨機的聲音之前的一種方式:
var sounds = [];
function playRepeatedly(sound, howManyTimes, callback) {
// this is similar to using `onend` when you create the sound
sound.once('end', function() {
// if there are more repetitions to go
if (howManyTimes > 1) {
// play one less time
playRepeatedly(sound, howManyTimes - 1, callback);
} else {
// if we're all done, call the callback
callback();
}
});
sound.play();
}
function playRandom() {
// pick a random sound
var sound = sounds[Math.floor(Math.random() * sounds.length) + 1];
// play it 4 times and then play a new random sound
playRepeatedly(sound, 4, function() {
// this is the callback, which just plays a new random sound
playRandom();
});
}
// load all the sounds ahead of time
var numberOfSounds = 3;
for (var i = 0; i < numberOfSounds; i++) {
sounds.push(new Howl({
src: ['audio/' + i + '.wav'],
autoplay: false,
loop: false,
volume: 1.0, // no more `onend` here
}));
}
// kick things off with the first random sound
playRandom();
好吧,最後你只是在播放聲音,而不是改變號碼 –
你能介紹一下如何改變號碼的方向嗎?我嘗試了在onend函數中的隨機數生成器,但不起作用 – dee
'number = Math.floor((Math.random()* 3)+ 1);''再次在'onend'中。 – Li357