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


<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>

你可能感兴趣的:(js)