我的网页上有图像,单击它们时会播放声音。
HTML 看起来像这样:
<span div="2" class="sound" onclick="playSound(this,'sounds/activity_1/letter_m_a_1_correct_v2.mp3');">
<img src="../../images/rainforest/letter_m/activity_1/a1_monkey.png" width="324px" height="274px" alt="Monkey" onclick="showPanelGroup_2();" />
</span>
<span div="3" class="sound" onclick="playSound(this,'sounds/activity_1/letter_m_a_1_incorrect_b.mp3');">
<img src="../../images/rainforest/letter_m/activity_1/a1_butterfly.png" width="324px" height="274px" alt="Butterfly" />
</span>
我当前使用以下 Javascript 代码在单击时一次暂停和播放一种声音:
function playSound(el,soundfile) {
if (el.mp3) {
if(el.mp3.paused) el.mp3.play();
else el.mp3.pause();
} else {
el.mp3 = new Audio(soundfile);
el.mp3.play();
}
}
如果单击两个图像,声音将重叠。我需要在单击第二个图像后立即停止播放第一个声音并播放第二个声音。
最佳答案
当您将 this
传递给 onclick
中的函数时,您正在为每个元素创建一个新的 MP3 播放器。
您要么需要使用单个元素来固定播放器,在这种情况下,您可以覆盖每次单击时正在播放的内容,或者您需要让每次单击将暂停信号发送给上的所有其他播放器页。
为每个玩家保留一个单独的玩家(就像您现在所做的那样)的好处是每个玩家都保留其进度,这样当您再次单击它时它就会恢复,所以这就是我将继续使用的示例。
以下是当您点击其中任何一个时暂停所有其他玩家的示例:
function pauseOthers(elements, me) {
Array.prototype.forEach.call(elements, function(el) {
if (el == me) { return; }
if (el.mp3) {
el.mp3.pause();
}
});
}
function playSound(el, soundfile) {
var allPlayers = document.getElementsByClassName('sound');
pauseOthers(allPlayers, el);
if (el.mp3) {
if(el.mp3.paused) el.mp3.play();
else el.mp3.pause();
} else {
el.mp3 = new Audio(soundfile);
el.mp3.play();
}
}
关于javascript - HTML 中的多个音频文件,如果单击两个,较旧的文件应停止播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45176768/