原生js实现播放器操作(随机播放、上/下一首、播放/暂停)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>播放器</title>
</head>
<body>
    <audio hidden controls="controls" 
     id='player'>...</audio>
     <button onclick="lastMusic()">上一首</button>
     <button onclick="playMusic(this)">播放</button>
     <button onclick="nextMusic()">下一首</button>
     <button onclick="shufflePlay()">随机播放</button>
</body>
<script type="text/javascript">
    let rootUrl = '../../Downloads/新专辑/林俊杰/'
    let player = document.getElementById('player')
    let isPlaying = true
    let songs = ['将故事写成我们 - 林俊杰.flac','不为谁而作的歌 - 林俊杰.flac','As I Believe - 林俊杰.flac','对的时间点 - 林俊杰.flac','Wonderland - 林俊杰.flac']
    let i = 0
    player.src = rootUrl + songs[i]
    player.addEventListener('ended', function () {  
        i++
        player.src = rootUrl + songs[i]//换地址
        player.play()
    }, false);
    function shuffle() {
        let i = songs.length;
        while (i) {
            let j = Math.floor(Math.random() * i--);
            [songs[j],songs[i]] = [songs[i], songs[j]];
        }
        console.log(songs);
    }
    function nextMusic(){
        if (++i>songs.length-1) {
            i=0
        }
        let song = songs[i]
        player.src = rootUrl + song
        player.play()
        console.log('正在播放第'+(i+1)+'首');
    }
    function lastMusic(){
        let song 
        i>0?--i:i=songs.length-1
        player.src = rootUrl + songs[i]
        player.play()
        console.log('正在播放第'+(i+1)+'首');
    }
    function shufflePlay(){
        shuffle()
        if(i!=0)
            i = 0
        player.src = rootUrl + songs[i]
        player.play()
    }
    function playMusic(ctrl){
        if(!player.paused){                 
            player.pause();
            ctrl.innerText = '播放'
        }else{
            player.play(); 
            ctrl.innerText = '暂停'
        }
    }

</script>
</html>
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页