0xSingularity
0xSingularity

Reputation: 570

How to play each audio element on a page (HTML, JQuery, Javascript)

O.k I have a page that has multiple audio elements on it. I am looking for a way to play each one, starting from the first, waiting for it to finish playing and then move on to the next audio element, until the last element. Is there any way possible to accomplish this? Thanks!

Edit:

I can't add a code sample because the audio elements are all added dynamically by PHP so it's a empty file before that.

Upvotes: 1

Views: 2350

Answers (2)

0xSingularity
0xSingularity

Reputation: 570

Based on @liam-schauerman answer, I actually came up with this solution:

var index = 0;
var audioElements = document.getElementsByTagName('audio');

function playNext(index) {
    audioElements[index].play();
    $(audioElements[index]).bind("ended", function(){
        index++;
        if(index < audioElements.length){
            playNext(index);          
        }
    });

}

$(document).ready(function() {
    $("#swig").click(function() {
        audioElements[index].play();

        $(audioElements[index]).bind("ended", function(){
             index = index + 1;
             if(index < audioElements.length){
                playNext(index);          
             }                        
        });


    });
});

I just blindly coded this. If someone would elaborated and why this works I would appreciate it.

Upvotes: 1

Liam Schauerman
Liam Schauerman

Reputation: 841

You can do this by storing each audio element in a queue. Lets say you store each element in an array audioElements.

var index = 0;
function playNext(index){
  audioElements[index].play(); //this will play the element
  audioElements[index].on('ended', function(){ //this will bind a function to the "ended" event
    //increment the index to target the next element
    index++;
    if(index < audioElements.length){
      //plays the next song and binds the function to the ended event again until the queue is empty
      playNext(index);          
    }
  }
}
playNext(index);

Upvotes: 2

Related Questions