我正在创建一个基于 web 的队列系统,我发现在音频部分很难,例如我想要按顺序播放音频
var sounds = [
new Audio("/audios/ding.wav"),
new Audio("/audios/nomor_antrian.wav")
];
for (var i=0; i<sounds.length; i++) {
sounds[i].play();
# If sounds[i] is stoped play sounds[i+1] <- what function in here
}
最佳答案
只需按住您正在播放的音频的当前索引,
并在 HTMLAudio 的 ended
中增加它事件:
var url = "https://dl.dropboxusercontent.com/s/";
var sounds = [
new Audio(url + "kbgd2jm7ezk3u3x/hihat.mp3"),
new Audio(url + "h2j6vm17r07jf03/snare.mp3"),
new Audio(url + "h8pvqqol3ovyle8/tom.mp3"),
new Audio(url + "1cdwpm3gca9mlo0/kick.mp3")
];
var currentIndex = 0; // keep track of the current index
sounds.forEach(function(sound) {
sound.onended = onended; // add the same event listener for all audios in our array
});
function onended(evt) {
currentIndex = (currentIndex + 1) % sounds.length; // increment our index
sounds[currentIndex].play(); // play the next sound
}
btn.onclick = sounds[0].play.bind(sounds[0]);
<button id="btn">play</button>
如果你不想创建这个超出范围的 currentIndex
变量,你也可以直接从你的数组中获取它:
var url = "https://dl.dropboxusercontent.com/s/";
var sounds = [
new Audio(url + "kbgd2jm7ezk3u3x/hihat.mp3"),
new Audio(url + "h2j6vm17r07jf03/snare.mp3"),
new Audio(url + "h8pvqqol3ovyle8/tom.mp3"),
new Audio(url + "1cdwpm3gca9mlo0/kick.mp3")
];
sounds.forEach(function(sound) {
sound.onended = onended;
});
function onended(evt) {
var currentIndex = (sounds.indexOf(this) + 1) % sounds.length; // get and increment our index
sounds[currentIndex].play(); // play the next sound
}
btn.onclick = sounds[0].play.bind(sounds[0]);
<button id="btn">play</button>
关于javascript - 使用javascript音频顺序播放音频声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45951416/