我对使用 javascript 并没有真正的经验,所以这个问题可能有点愚蠢。我目前正在尝试开发音板。一切正常,除了一件事,我想在单击另一个按钮时停止声音,我真的不知道该怎么做。
这是我想做的事的一个例子: 我单击按钮 1,播放声音,当声音仍在播放时,我单击按钮 2,按钮 1 的声音停止,而按钮 2 的声音开始播放。(每个按钮依此类推)
HTML代码:
function EvalSound(soundobj) {
var thissound = document.getElementById(soundobj);
thissound.play();
}
audio {
visibility: hidden;
}
<audio class="audio" id="a" src="" controls preload="auto" autobuffer></audio>
<audio class="audio" id="b" src="b.wav" controls preload="auto" autobuffer></audio>
<audio class="audio" id="c" src="c.mp3" controls preload="auto" autobuffer></audio>
<input type="button" class="button" value="Button 1" onClick="EvalSound('a')">
<input type="button" class="button" value="Button 2" onClick="EvalSound('b')">
<input type="button" class="button" value="Button 3" onClick="EvalSound('c')">
最佳答案
如果您调用 thissound.pause()
,它将停止播放声音。您想要做的是能够在您的函数结束并且局部变量已被删除后调用 thissound.pause()
。这意味着您需要将它存储在一个全局变量中,例如,您可以调用 currentsound
,这样您就可以在另一个 EvalSound
调用中访问它。这会给你带来这样的东西:
var currentsound;
function EvalSound(soundobj) {
currentsound.pause();
var thissound = document.getElementById(soundobj);
thissound.play();
currentsound = thissound;
}
然而,这给我们带来了 2 个问题。当您调用 EvalSound
时,之前的声音会暂停,当再次调用相同的声音时,它将从暂停时的位置开始播放。因此我们需要设置它需要开始播放的时间。另一个问题是当你第一次调用EvalSound
时,currentsound
会是undefined,调用currentsound.pause();
会报错.为了解决这个问题,我们可以添加以下内容:
var currentsound;
function EvalSound(soundobj) {
if(currentsound)
{
currentsound.pause();
}
var thissound = document.getElementById(soundobj);
thissound.currentTime = 0;
thissound.play();
currentsound = thissound;
}
关于javascript - 用javascript停止html声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28004324/