Search code examples
html5-audio

How to play multiple audio files one by one in html 5?


I would like to play multiple audio files one by one. I have read the same question, but I have found the links to the original answer not working and question unanswered.

Original answer

<audio id="mySound" controls><source src="http://www.hvalur.org/audio/uploaded_files/ds_umkomuleysi_0_0.mp3" type="audio/mpeg"></audio>

<audio id="mySound1" ><source src="http://www.hvalur.org/audio/uploaded_files/ds_ljosmyndavel_0_0.mp3" type="audio/mpeg"></audio>

I want the first sound started by the user action (pressing the play button) and then the following sound(s) playing one by one. The usage of this example will be practising of understanding of the telephone numbers read by native speaker.


Solution

  • I would do something like that:

    var mySound = document.getElementById("mySound");
    var mySound1 = document.getElementById("mySound1");
    var mySound2 = document.getElementById("mySound2");
    var mySound3 = document.getElementById("mySound3");
    
    var mySoundArray = [mySound, mySound1, mySound2, mySound3];
    var mySoundArrayPos = 0;
    
    var myButton = document.getElementById("myButton");
    myButton.addEventListener("click", function(event) {
        mySound.play();
        mySoundArrayPos = 0;
        startSoundTimer();
    });
    
    const startSoundTimer = () => {
        var mySoundTimer = setInterval(() => {
            if (mySoundArray[mySoundArrayPos].currentTime >= mySoundArray[mySoundArrayPos].duration) {
                if (mySoundArrayPos < mySoundArray.length -1) {
                    mySoundArrayPos += 1;
                    mySoundArray[mySoundArrayPos].play();
                } else {
                    clearInterval(mySoundTimer);
                }
            }
        }, 10);
    };
    

    I don't know if the 10ms are a bit too fast, but I think, it's legit.