Playing audio sound sequencely with javascript audio

醉酒当歌 提交于 2021-01-28 12:19:58

问题


I'm creating a queue system based on web, and i find it difficult on the audio part, i want audio playing sequencely, for example

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:


Simply hold the current index of the audio you're playing,
and increment it in HTMLAudio's ended event :

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>

And if you don't want to create this out of scope currentIndex variable, you can also get it directly from your array :

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>


来源:https://stackoverflow.com/questions/45951416/playing-audio-sound-sequencely-with-javascript-audio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!