在页面上连续播放随机声音 [英] Playing random sounds continuously on the page

查看:22
本文介绍了在页面上连续播放随机声音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑:

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

我想做一个非常简单的页面,它会连续播放随机歌曲.但我想不通.它只播放一首随机歌曲然后停止.顺便说一下,我要扩展歌曲列表.这只是一个原型.

I wanted to make a very simple page which is going to play random songs continuously. But I couldn't figure it out. It plays just one random song and stops. By the way I am going to extend the song list. This is just a prototype.

推荐答案

这是我更改的内容:

  1. 重构了您定义列表的方式
  2. 创建了一个选择新歌曲的功能(它不选择上次播放的歌曲)
  3. getElementsByTag() 更改为 getElementById()
  4. 为了调试,我添加了控件
  1. Refactored how you define your list
  2. Created a function to choose a new song (It doesn't pick the last played song)
  3. Changed getElementsByTag() to getElementById()
  4. For debugging I added controls

代码:

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

这篇关于在页面上连续播放随机声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆