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

时间:2016-06-04 21:41:55

标签: javascript html variables audio

{{1}}
  

您好,

     

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

     

感谢您的帮助,

1 个答案:

答案 0 :(得分:1)

以下是我改变的内容:

  1. 重新定义列表的方式
  2. 创建了一个选择新歌的功能(它不会选择最后播放的歌曲)
  3. getElementsByTag()更改为getElementById()
  4. 对于调试我添加了控件
  5. 代码:

    <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>