Aaron
Aaron

Reputation: 63

Play MP3 files in order without HTML5 audio with JavaScript

I'm trying to play three MP3 files one after another using Javascript without the HTML5 audio tag. [I'm working within Articulate Storyline which is an authoring tool for eLearning. It supports Javascript within files but not HTML]

So far, the best I've got is the following which plays all at the same time:

function myFunction() {
    var audio1 = new Audio('http://www.mysite.co.uk/h/welcome.mp3');
    var audio2 = new Audio('http://www.mysite.co.uk/h/name.mp3');
    var audio3 = new Audio('http://www.mysite.co.uk/h/cont.mp3');

    audio1.play();
    audio2.play();
    audio3.play();
}

I've considered a 'wait' function, but I only know how to do this properly with JQuery, and if I'm recalling correctly, Articulate Storyline does not support JQuery even if it is hosted elsewhere.

Any help with this is greatly appreciated

Upvotes: 0

Views: 2141

Answers (3)

amin
amin

Reputation: 581

You can use this simple method for play unlimited files:

PlayAll= function (pathList) {

    if(pathList.length>0){
      var audio = new Audio(pathList[0]);
      if(pathList.length>1){
         var count = 1;
         $(audio).on('ended', function () {
            if (count < pathList.length) {
               audio.src =  pathList[count];
               audio.play();
               count++;
            }
         });
      }
      audio.play()
   }
};

Upvotes: 0

KpTheConstructor
KpTheConstructor

Reputation: 3291

I would suggest you use the audio onended event . Just listen for one player to stop then play the next .

Example : One way is to add your players to an array for better control

var players = [audio1,audio2,audio3];

    var counter = 0;

    audio1.onended = playNext;



    function playNext(){
         if(counter <= players.length){
          counter++
          players[counter].play();
          players[counter].onended = playNext;
    }
   }

oneneded : http://www.w3schools.com/tags/av_event_ended.asp

Hope this helps

Upvotes: 1

adeneo
adeneo

Reputation: 318312

You can use an event handler that listens for the audio play to end, and then play the next one etc.

function play(audio) {
    audio.play();
    return new Promise(function(resolve, reject) {
        audio.addEventListener('ended', resolve);
    });
}

function myFunction() {
    var audio1 = new Audio('http://www.mysite.co.uk/h/welcome.mp3');
    var audio2 = new Audio('http://www.mysite.co.uk/h/name.mp3');
    var audio3 = new Audio('http://www.mysite.co.uk/h/cont.mp3');

    play(audio1).then(function() {
        return play(audio2);
    }).then(function() {
        return play(audio3);
    });
}

Upvotes: 2

Related Questions