使用javascript音频顺序播放音频声音

时间:2017-08-30 03:27:41

标签: javascript html5 audio

我正在创建一个基于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
}

1 个答案:

答案 0 :(得分:1)

只需按住您正在播放的音频的当前索引即可 并在HTMLAudio的ended事件中增加它:

&#13;
&#13;
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]);
&#13;
<button id="btn">play</button>
&#13;
&#13;
&#13;

如果您不想创建超出范围的currentIndex变量,您也可以直接从您的数组中获取它:

&#13;
&#13;
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]);
&#13;
<button id="btn">play</button>
&#13;
&#13;
&#13;