chejnik
chejnik

Reputation: 229

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.

Upvotes: 0

Views: 3112

Answers (2)

Pykara_Developer
Pykara_Developer

Reputation: 318

Javascript 
=============== `playaudio(i) {
    var thisme = this;
    var audio = new Audio(thisme.model.audioFiles[i].audioUrl);
    audio.play();    
      audio.addEventListener("ended", function () {
        i = i + 1;
        console.log(i);
        if (i < thisme.model.audioFiles.length) {
          audio.src = thisme.model.audioFiles[i].audioUrl;
          audio.play();
        }
    }, false);
    }    
  }`



HTML
====`<span class='chunkAudio' (click)="playaudio(0)">
           <img class='playbtn' src="{{model.playerImageUrl}}" />
        </span>`

Upvotes: 0

Kurt Lagerbier
Kurt Lagerbier

Reputation: 200

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.

Upvotes: 1

Related Questions