gpt4 book ai didi

javascript - 播放不重复的随机声音

转载 作者:行者123 更新时间:2023-11-30 10:24:14 24 4
gpt4 key购买 nike

我希望有一个图像,当点击时播放一个声音剪辑(来自声音剪辑列表)而不重复相同的剪辑(直到用户浏览整个声音列表。)

目前我的代码可以工作,但随机播放我的任何一个声音片段并重复很多次。

如果有人知道如何调整它以使其在重复之前至少播放列表中的每个剪辑一次,那就太棒了!

这是我目前使用的代码:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
function playSounds() {
var sounds = [
"AUDIO URL",
"AUDIO URL",
"AUDIO URL",
"AUDIO URL",
"AUDIO URL"
];

var index = Math.floor(Math.random() * (sounds.length));
$("#element").html("<embed src=\"" + sounds[index] + "\" hidden=\"true\" autostart=\"true\" />");
}
</script>

<a onclick="playSounds()"><img src="IMAGE URL" width="300px" id="ImageButton1"></a>

我猜这与代码的 Math.random() 部分有关?

最佳答案

您可以将数组用作播放列表,并将播放的声音保存在第二个数组中。查看我的JSfiddle

<a onclick="playSounds()">
<img src="http://www.stephaniequinn.com/Ani-Piano.gif" width="300px" id="ImageButton1">
</a>
<div id="element"></div>
<script>
var sounds = ["http://www.stephaniequinn.com/Music/Allegro%20from%20Duet%20in%20C%20Major.mp3",
"http://www.stephaniequinn.com/Music/Canon.mp3",
"http://www.stephaniequinn.com/Music/Handel%20Royal%20Fireworks%20-%2007.mp3",
"http://www.stephaniequinn.com/Music/Commercial%20DEMO%20-%2009.mp3"],
oldSounds = [];

var playSounds = function () {
var index = Math.floor(Math.random() * (sounds.length)),
thisSound = sounds[index];

oldSounds.push(thisSound);
sounds.splice(index, 1);

if (sounds.length < 1) {
sounds = oldSounds.splice(0, oldSounds.length);
}

$("#element").html("<audio autoplay><source src=\"" + thisSound + "\" type=\"audio/mpeg\"><embed src=\"" + thisSound + "\" hidden=\"true\" autostart=\"true\" /></audio>");
}
</script>

关于javascript - 播放不重复的随机声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20227266/

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