I am trying to iterate through a playlist, but not skip to the next item until the current song is done playing or until a new song in the playlist is chosen. Currently my array is iterated, but does not wait for the current song to finish playing.
HTML:
<li mp3="song1.mp3"></li>
<li mp3="song2.mp3"></li>
<li mp3="song3.mp3"></li>
<li mp3="song4.mp3"></li>
JavaScript:
var player = new MediaElementPlayer('audio');
playlist = ['song1.mp3', 'song2.mp3', 'song3.mp3', 'song4.mp3'];
$('li').click(function() {
for (var i = playlist.indexOf($(this).attr('mp3')); i < playlist.length; i++) {
player.setSrc(playlist[i]);
player.play();
player.addEventListener('ended', function(e) {
player.setSrc(playlist[i]);
player.play();
}, false);
}
});
You’re running a plain loop, so a bunch of
.play()calls are run right after each other. Instead, run only one.play(), and call the next one when the song has ended. This can be done by calling recursively. Also, usedata-mp3attributes and.data("mp3"), because that’s the only valid way to define custom attributes.