【问题标题】:Playing random sounds continuously on the page在页面上连续播放随机声音
【发布时间】:2016-06-04 21:41:55
【问题描述】:

考虑:

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

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

【问题讨论】:

    标签: javascript html variables audio


    【解决方案1】:

    这是我改变的:

    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>
    

    【讨论】:

    • 感谢您的帮助,但它没有播放任何歌曲。你试过了吗?
    • 谢谢。这一次,它播放了一首歌曲,然后停止了。
    • 没问题!在你走之前,我只是想确保你知道我的代码是如何工作的,否则它对你毫无帮助。
    • @Caglar 我添加了一些 cmets :)
    • 现在更容易看到发生了什么。感谢您对 Oisin 的所有帮助。
    猜你喜欢
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多