1.通过触发onended事件调用函数改变音频的src(地址)来达到切歌
<audio autoplay="autoplay" src="cfc.mp3" id="song" onended="change()"></audio>
#onended DOM事件对象
<script type="text/javascript">
var song = document.getElementById('song');
music =new Array('音乐存放的地址eg:media/xxx.mp3','xxxxxx','xxxx');
function change() {
if(song.ended){#判断音乐是否播放完
index = Math.floor(Math.random()*music.length);
#Math.floor()就近取整
#Math.random() 0-1内的随机数 Math.random()*10代表0-10内的随机数
song.src=music[index];
song.play();
}
}
</script>
2.通过设置监听事件
<script type="text/javascript">
var song = document.getElementById('song');
music =new Array('media/cfc.mp3','media/fhm.mp3');
song.addEventListener("onended" ,function(){
if(song.ended){
index = Math.floor(Math.random()*music.length);
song.src=music[index];
song.play();
}
});
</script>
照搬以上代码是运行不了的,把他放到window.onload=function(){ } 去,才能运行
element.addEventListener(event, function, useCapture)