亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何僅在觸發播放按鈕時讓音樂自動播放?

如何僅在觸發播放按鈕時讓音樂自動播放?

函數式編程 2021-11-18 20:20:29
我正在嘗試在我的網站上實現一個音頻欄,它會從歌曲列表中隨機選擇要播放的歌曲。音樂應該開始,但只有在按下播放按鈕時才開始,當一首歌曲結束時,自動播放下一首歌曲。下面的代碼工作正常,除了前面提到的,音樂在沒有按下播放按鈕的情況下自行播放。有誰知道如何解決這個問題?我嘗試設置player.autoplay=true;為,false但下一首歌曲不會自動播放。<audio id="audioplayer" controls> <!-- Remove the "Controls" Attribute if you don't want the visual controls --></audio><script>    var lastSong = null;    var selection = null;    var playlist = ["sounds/0.mp3", "sounds/1.mp3", "sounds/2.mp3"]; // List of Songs    var player = document.getElementById("audioplayer"); // Get Audio Element    player.autoplay=true;    player.addEventListener("ended", selectRandom); // Run function when song ends    function selectRandom(){        while(selection == lastSong){ // Repeat until different song is selected            selection = Math.floor(Math.random() * playlist.length);        }        lastSong = selection; // Remember last song        player.src = playlist[selection]; // Tell HTML the location of the new Song    }    selectRandom(); // Select initial song    player.play(); // Start Song</script>
查看完整描述

2 回答

?
慕勒3428872

TA貢獻1848條經驗 獲得超6個贊

你有沒有試過刪除 player.play();



查看完整回答
反對 回復 2021-11-18
?
慕容森

TA貢獻1853條經驗 獲得超18個贊

創建一個按鈕并添加一個onclick屬性,移動selectRandom() 到一個按鈕onclick函數,如下所示:


var player = document.getElementById("audioplayer");

var lastSong = null;

var selection = null;

var playlist = ["https://www.soundjay.com/button/sounds/beep-07.mp3", "https://www.soundjay.com/button/sounds/button-2.mp3", "https://www.soundjay.com/button/sounds/button-3.mp3"]; // List of Songs


function start() {

   player.play();

   player.addEventListener("ended", selectRandom);

   

    function selectRandom(){

        while(selection == lastSong){ // Repeat until different song is selected

            selection = Math.floor(Math.random() * playlist.length);

        }

        lastSong = selection; // Remember last song

        player.src = playlist[selection]; // Tell HTML the location of the new Song


    }

    player.autoplay=true;

    selectRandom();

}

<audio id="audioplayer" controls ></audio>


<button onclick="start()"> Play </button>


查看完整回答
反對 回復 2021-11-18
  • 2 回答
  • 0 關注
  • 222 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號