利用js实现的音乐简易播放器

<html>

<head>
    <meta charset="utf-8">
    <meta name="author" content="dongfeng">
    <title></title>
    <script>
    var musics = [
    '1.mp3',
    '2.mp3',
    '3.mp3',
    '4.mp3',
    '2.mp3'
];
//定义正在播放的音频的索引
var index = 0;
//记录顺序和随机的变量
var playType;
window.onload = function() {
    var typeSel = document.getElementById('typeSel');
    //当用户更改下拉菜单选项时,改变播放方式
    typeSel.onchange = function() {
        console.log(typeSel.value)
        window.playType = typeSel.value;
    }
    var player = document.getElementById('player');
    //页面加载时播放的第一个文件
    player.src = musics[index];
    player.addEventListener('ended',myFunction)
    function myFunction() {
        
        if(playType == 'random') {
            index = Math.floor(Math.random() * musics.length);
            console.log(index)
            player.src = musics[index];
        } else {
            //播放下一个音频
            player.src = musics[++index % musics.length]
        }
        player.play();
    }
}
    </script>

    <style>
        #typeSel {
    margin-bottom: 30px;
    width: 160px;
}</style>
</head>

<body>
<h2>音乐播放器</h2>
<select id="typeSel">
    <option value="sequence">顺序播放</option>
    <option value="random">随机播放</option>
</select><br />
<audio id="player" controls>你的浏览器不支持audio元素</audio>


</body>

</html>

audio中的onended方法不知怎么只有用事件监听的方法才有用,<element onended="myScript">和object.onended=function(){myScript};都不起作用,只有object.addEventListener("ended", myScript);才起作用

posted @ 2017-04-12 23:29  Athena-web  阅读(3665)  评论(0编辑  收藏  举报