Evgenij Reznik
Evgenij Reznik

Reputation: 18614

Playlist with JavaScript

I have some audio files (a.mp3, b.mp3, c.mp3) and a random array (b, c, a). I want to play these audio files in the given order, like in a playlist.
This is my code so far:

<audio id="player" />

<script>
//... extract

var player = document.getElementById('player');
player.src="audio/"+array[0]+".mp3";
player.play(); // play first file

for(c = 0; c < array.length; c++){
var next = "audio/"+array[c]+".mp3";
document.write(next);
    player.addEventListener("ended",function() {
        this.src = next;
        this.play();
    });
}
</script>

The problem is, after playing the first file, the second file is being played forever. It never stops and the next file can't be played.

Upvotes: 0

Views: 173

Answers (1)

bfavaretto
bfavaretto

Reputation: 71939

You don't need a loop, decide what's next from the "ended" listener:

var current = 0;
// ...
player.addEventListener("ended",function() {
    current = current + 1 < array.length ? ++current : 0;
    this.src = "audio/" + array[current] + ".mp3";
    this.play();
});

Upvotes: 2

Related Questions