gpt4 book ai didi

javascript - HTML: 多个 onclick 音频文件,让最后一个停止

转载 作者:行者123 更新时间:2023-11-28 03:05:06 25 4
gpt4 key购买 nike

我一直访问这个网站来寻找解决方案,但我找不到问题的答案。

我想将多个音频文件添加到一个页面。所以我使用了以下编码。这是做什么的,当您单击一个文件时,它开始播放音乐,当您单击下一个文件时,其余的将暂停。这就是我想要的。

但我还希望每个文件都有播放/暂停选项;所以当你点击“Night Swim”的“listen/pause”链接时,它开始播放,当你再次点击同一个链接时,它就会停止。

有什么办法可以做到这一点吗?我对 Javascript 不是很在行,我尝试了各种其他代码,但似乎都无法按我想要的方式工作。

我希望有人能帮助我,我希望我的问题得到正确解释(我是荷兰人,我为我的英语道歉:S)

这是我的代码:

<audio id="1"> 
<source src="everynight-snippet.mp3" type='audio/mpeg'>
</audio>
<audio id="2">
<source src="nightswim-snippet.mp3" type='audio/mpeg'>
</audio>

Every Night (<a href="#" onclick="aud_play_pause('1')">Listen/Pause</a>)
Night Swim (<a href="#" onclick="aud_play_pause('2')">Listen/Pause</a>)

和脚本:

<script>
ids = new Array(2); // an array with total number of ids
function aud_play_pause(idNumber) {
var idNumber = document.getElementById(idNumber);

for(var i=0; i<ids.length; i++){
document.getElementById(i+1).pause(); // Pause all ids before playing next file.
document.getElementById(i+1).currentTime = 0; // Set the time back to zero, else it will replay from the pause point.
}

idNumber.play();
}
</script>

总结一下:

  • 如果我点击第一首歌曲 (Every Night),它就会开始播放。当我再次点击它时,它应该会停止播放。
  • 如果我在播放第一首歌曲时单击第二首歌曲 (Night Swim),则第一首歌曲应该停止播放而第二首歌曲应该开始播放。如果我再次点击第二首歌曲,它应该会停止。
  • 等等

最佳答案

您可以使用 currentTime 属性检查 idNumber 音频是否正在播放,如果没有则启动它。否则,如果当前正在播放,您仍然可以停止所有这些播放。

ids = new Array(2); // an array with total number of ids
function aud_play_pause(idNumber) {
var clickedAudio = document.getElementById(idNumber);

for (var i = 0; i < ids.length; i++) {
if ((i + 1) == idNumber && clickedAudio.currentTime == 0) { // if it's the current one and is not playing
clickedAudio.play(); // start it
} else { // either not the current one, or the current one but it is playing
document.getElementById(i + 1).pause(); // Pause all ids before playing next file.
document.getElementById(i + 1).currentTime = 0; // Set the time back to zero, else it will replay from the pause point.
}

}

}

通过 for 暂停所有元素,您编写代码的方式。

关于javascript - HTML: 多个 onclick 音频文件,让最后一个停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32953211/

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