我的文件夹中有很多 MP3 文件。
当我进入一个页面时,我想要播放该播放列表中的歌曲。这首歌结束后,我想播放一首新的(不是同一首)等等。
<script type="text/javascript">
var song = ["../audio/1.mp3" , "../audio/2.mp3", "../audio/3.mp3", "../audio/4.mp3", "../audio/5.mp3" ];
var soundFile = song[Math.floor(Math.random()*song.length)];
document.write("<embed id='sound' src='" + soundFile + "' loop='true' type='audio/mpeg' controller='false' height='0' width='0'>");
</script>
怎么了,因为它总是播放同一首歌。
最佳答案
使用已定义的嵌入元素并设置src
属性。
<embed id='sound' loop='true' type='audio/mpeg' controller='false' height='0' width='0'>
<script type="text/javascript">
var songs = ["../audio/1.mp3" , "../audio/2.mp3", "../audio/3.mp3", "../audio/4.mp3", "../audio/5.mp3" ];
var remainingSongs = songs;
var el = document.getElementById("sound");
var pickSong = function(){
// No songs left?
if(!remainingSongs.length) {
remainingSongs = songs;
}
// Pick song
var index = Math.floor(Math.random() * (remainingSongs.length - 1));
var soundFile = remainingSongs[index];
// Remove song from array
remainingSongs.splice(index, 1);
el.setAttribute("src", soundFile);
}
pickSong();
el.addEventListener("ended", pickSong, false);
</script>
关于javascript - 具有随机播放列表的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34008333/