超简单的JS网页音乐播放器,代码简单明了,小白也会用。当你打开HTML网页时,JS会自动触发 window.onload事件,并调用 playRandomSong函数播放随机歌曲。播放器会自动选择一个歌曲进行播放,在播放完一首歌曲后自动随机选择另一首歌曲继续播放。
<!DOCTYPE html> <html> <head> <title>音乐播放器</title> <script> window.onload = function() { var audio = document.getElementById("audioPlayer"); audio.addEventListener('ended', playRandomSong); playRandomSong(); }; function playRandomSong() { var songs = [ //这里填写音乐文件的URL,多个URL用换行符分割 ]; var randomIndex = Math.floor(Math.random() * songs.length); var audio = document.getElementById("audioPlayer"); audio.src = songs[randomIndex]; audio.play(); var currentSongUrl = document.getElementById("currentSongUrl"); currentSongUrl.textContent = "正在播放:" + songs[randomIndex]; } </script> </head> <body> <h1 id="currentSongUrl"></h1> <audio id="audioPlayer" controls></audio> </body> </html>