我有一组 3-5 秒的音频文件,我想通过单击按钮对其进行随机化。
const audioArray = ["sound1.mp3", "sound2.mp3", "sound3.mp3"];
function playRandomAudio() {
const audioIndex = Math.floor(Math.random() * audioArray.length);
const audio = new Audio(audioArray[audioIndex]);
audio.pause();
audio.currentTime = 0;
audio.play();
}
<button onclick="playRandomAudio()" type="button">Play Audio</button>
问题:当新一首曲目开始时,我无法让最后一首曲目停止播放。如果您使用下面的代码单击按钮,则第二次单击会在第一次单击的基础上播放曲目,第三次单击会在另外两个音轨之上覆盖另一个音轨。
建议?
在 Reddit 上得到答案:
const audioArray = ["sound1.mp3", "sound2.mp3", "sound3.mp3"];
let currentAudio;
function playRandomAudio() {
// Stop the current audio if it exists
if (currentAudio) {
currentAudio.pause();
currentAudio.currentTime = 0;
}
const audioIndex = Math.floor(Math.random() * audioArray.length);
const audio = new Audio(audioArray[audioIndex]);
// Set the currentAudio to the new audio
currentAudio = audio;
// Play the new audio
audio.play();
}
谢谢!