【发布时间】:2019-10-13 11:52:57
【问题描述】:
我正在尝试在我的网站上实现一个音频栏,它可以从歌曲列表中随机选择要播放的歌曲。音乐应该开始,但只有在按下播放按钮时才会开始,当一首歌曲结束时,会自动播放下一首歌曲。
下面的代码工作正常,除了前面提到的,音乐自己播放,没有按下播放按钮。有谁知道如何解决这个问题?
我尝试将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>
【问题讨论】:
-
将
selectRandom();移动到按钮点击事件并移除 player.play(); // 开始歌曲 -
能否请您提供按钮单击事件的代码,因为我还是个初学者。提前谢谢你。
标签: javascript html