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 is giving me an error on audio.src = (playlist [i]) ;, Does anyone know how to solve this?
+3
source to share
1 answer
You need to use 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();
+6
source to share