为了账号安全,请及时绑定邮箱和手机立即绑定

如何仅在触发播放按钮时让音乐自动播放?

如何仅在触发播放按钮时让音乐自动播放?

函数式编程 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 关注
  • 176 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信