gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 06:48:03 24 4
gpt4 key购买 nike

考虑:

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com