Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 365
Kryptonous Avatar asked Dec 19 '22 04:12

Kryptonous


1 Answers

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();
like image 171
Arun P Johny Avatar answered Dec 24 '22 01:12

Arun P Johny