itzChris itzChris - 6 months ago 28
Javascript Question

Playing 2 audio files one after the other

I've already looked on the few similar questions on here and can't find anything relevant. I have 2 audio files. The first plays through when the page loads, and it works fine. I want the 2nd audio file to play as soon as the first one ends and I also need the 2nd file too loop indefinitely. Here is what I have tried so far:

<body>
<audio autoplay id="audio_1" src="./audio1.wav"></audio>
<audio loop id="audio_2" src="./audio_2.wav"></audio>
</body>


And the javascript:

var audio = document.getElmentById("audio_1");
audio.addEventListener("ended", function() {
audio.src = "./audio_2.wav";
audio.play();
});


Like I said, the 1st file plays fine, but then the 2nd file doesn't play at all. Any ideas would be much appreciated, thanks.

Answer

You should try creating two vars :

var audio = document.getElmentById("audio_1");
var audio2 = document.getElmentById("audio_2");
audio2.pause();
audio.addEventListener("ended", function() {
   audio_2.play();
});

EDIT: you had typos errors in "getElement"

here is the new code

var audio = document.getElementById("audio_1");
var audio2 = document.getElementById("audio_2");
audio2.pause();
audio.addEventListener("ended", function () {
 audio2.play();
});