我试图使用howler.js播放随机音频文件,然后超时选择一个不同的随机文件,使其循环播放。我在播放和循环播放,但每次循环都使用相同的文件。唯一的随机选择是在初始负载上。
这就是我所拥有的:
var number = Math.floor((Math.random() * 3) + 1);
var sound1 = new Howl({
src: ['audio/'+number+'.wav'],
autoplay: false,
loop: false,
volume: 1.0,
onend: function() {
sound1.play()
}
});
sound1.play()
这会愉快地播放音频文件夹中3个随机wav文件之一,但仅在加载时随机选择。然后,同一文件将无限循环。
对javascript来说还很陌生,因此不胜感激。谢谢。
最佳答案
这个怎么样?
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();
更新
回答下面的评论,这是在继续播放下一个随机声音之前重复播放每种声音四次的一种方法:
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();
关于javascript - 每次在javascript循环上随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39359189/