How do I loop through a javascript array of audio files?

Kryptonous picture Kryptonous · May 17, 2015 · Viewed 9.6k times · Source

I have a small question about using an array containing Audio-sources (links) in a for loop.

This is my code, basically:

    var audio = new Audio();
    var playlist = new Array('sounds/song0.m4a', 'sounds/song1.m4a', 'sounds/song2.m4a');

        for (var i = 0; i <= playlist.length; i++){
    audio.src = (playlist[i]);
    audio.volume = 0.3;
    audio.loop = false;
    if (audio.ended = true)
        i++;

    if (i = 2) {
        i = 0;
    }

My console gives me an error on the audio.src = (playlist[i]); . Anyone knows how to solve this?

Answer

Arun P Johny picture Arun P Johny · May 17, 2015

You need to use the ended event

var audio = new Audio(),
    i = 0;
var playlist = new Array('http://www.w3schools.com/htmL/horse.mp3', 'http://demos.w3avenue.com/html5-unleashed-tips-tricks-and-techniques/demo-audio.mp3');

audio.addEventListener('ended', function () {
    i = ++i < playlist.length ? i : 0;
    console.log(i)
    audio.src = playlist[i];
    audio.play();
}, true);
audio.volume = 0.3;
audio.loop = false;
audio.src = playlist[0];
audio.play();