简体   繁体   中英

Play multiple audio files in sequence (Javascript)

Can someone explain this behaviour? I have a button and when it is clicked, I need to play 6 mp3 files in sequence. I'm using the onended event handler:

var index;
playButton.onclick=function(){
  index = 0;
  conj[0].play();
  conj[index].onended = function() {
    if(index < conj.length){
      index++;
      conj[index].play();
    }
  };
}

With the index++ line in the code, I am trying to increment index so that it plays the next audio file in the array conj once the current audio file has finished playing, etc. until it plays the 6th and final audio file in the array. But onended only fires once. in other words conj[0] plays, then onended gets fired and then conj[1] plays then that's it. onended doesn't fire again. Now When I comment out the "index++;" line, the first mp3 conj[0] gets played and onended keeps firing so conj][0] just plays in a loop. In other words onended only keeps firing if I don't change the value of index. I know it's something stupid but i've spent too much time trying to figure it out.

You only have the first audio's "onended" event handled. When this line is called. conj[index].onended = function() index was 0. What you need to do is to have a loop that does something like this

for (var idx = 0; idx < conj.length - 1 ; idx++) {
conj[idx].onended = function() {
      conj[idx+1].play();
  };
}

Which supply and handler for each audio (except the last one) that says "Once I'm done playing trigger the next audio to play."

full example

var index;
playButton.onclick=function(){
  // sets up each audio file's onended event to play the next audio file
  for (var idx = 0; idx < conj.length - 1 ; idx++) {
    conj[idx].onended = function() {
      conj[idx+1].play();
    };
  }
  // start playing the first audio.
  conj[0].play();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM