我试图遍历播放列表,但在当前歌曲播放完毕或选择播放列表中的新歌曲之前,不会跳到下一项。目前我的数组是迭代的,但不等待当前歌曲完成播放。
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);
}
});
最佳答案
你运行的是一个普通的循环,所以一堆.play()
调用紧接着运行。相反,只运行一个.play()
,并在歌曲结束时调用下一个。这可以通过递归调用来实现。另外,使用data-mp3
属性和.data("mp3")
,因为这是定义自定义属性的唯一有效方法。
$("#playlist li").click(function() {
var start = playlist.indexOf($(this).data("mp3"));
(function play(i) {
if(i < playlist.length) { // if we're not at the end of the playlist yet
player.setSrc(playlist[i]);
player.play();
player.addEventListener("ended", function(e) {
play(i + 1); // done, so call with next index
}, false);
}
})(start); // call it with first index now
});
关于javascript - javascript在特定点遍历数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13845462/