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

标签 javascript html variables audio

考虑:

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

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

最佳答案

这是我所做的更改:

  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>

关于javascript - 在页面上连续播放随机声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37635281/

相关文章:

php - 表单提交时未定义索引

c - 在C中为两种不同的变量类型输入一次

c - 为什么函数中的非静态变量被初始化为 0 以及为什么它变成静态的?

javascript - 如何在浏览器中预取返回 JSON 格式数据的 ajax 调用

html - 超链接图像容器太宽

javascript - 无效的表达式术语 '='

html - 如何在使用 Angular 2 通过 webkitspeech 录制时动态地将文本添加到文本区域?

javascript - 如果数字在数字部分中

javascript - 无法在 Javascript 中使用 getAttribute() 从表中检索数据

javascript - JS 正则表达式用于匹配 URL 中的不同 #tags