Aaron Aaron - 2 months ago 20
jQuery Question

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

Answer

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);
    });
}