在页面上连续播放随机声音



考虑:

<!DOCTYPE html>
<html>
    <body>
        <audio>
        </audio>
        <script language="javascript">
            var playlist = new Array;
                playlist[0] = "sounds/0.mp3";
                playlist[1] = "sounds/1.mp3";
                playlist[2] = "sounds/2.mp3";
            var song = document.getElementsByTagName("audio")[0];
            song.innerHTML = '<source src="' + playlist[Math.floor(Math.random() * playlist.length)] + '" type="audio/mpeg">';
            song.autoplay = true;
            document.getElementsByTagName("audio")[0].addEventListener("ended", function(song)
            {
                <!-- Play another random song -->
            });
        </script>
    </body>
</html>

我想制作一个非常简单的页面,它将连续播放随机歌曲。但是我想不通。它只播放一首随机歌曲并停止。顺便说一下,我将扩展歌曲列表。这只是一个原型。

这是我更改的内容:

  1. 重构了定义列表的方式
  2. 创建了一个选择新歌曲的函数(它不会选择最后播放的歌曲)
  3. getElementsByTag()更改为getElementById()
  4. 为了调试,我添加了控件

法典:

<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 the song ends
    function selectRandom(){
        while(selection == lastSong){ // Repeat until a different song is selected
            selection = Math.floor(Math.random() * playlist.length);
        }
        lastSong = selection; // Remember the last song
        player.src = playlist[selection]; // Tell HTML the location of the new song
    }
    selectRandom(); // Select initial song
    player.play(); // Start song
</script>

最新更新