javascript Javascript在点击时播放声音,第二个按钮点击停止第一个声音

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22926271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:02:33  来源:igfitidea点击:

Javascript play sound on click, second button click stop first sound

javascriptaudio

提问by Gav

I have this code that on button press it plays a sound, What I want is when one sound is playing from first click if you click another button before its over it stops the first one and plays the next one you clicked on.

我有这个代码,在按下按钮时它会播放声音,我想要的是当一个声音从第一次点击播放时,如果你在它结束之前点击另一个按钮,它会停止第一个并播放你点击的下一个。

Any ideas would be great.

任何想法都会很棒。

<!DOCTYPE html>
<head>
<title>Sounds</title>
</head>

<body>

<audio id="sound1" src="sounds/sound1.mp3"></audio>
<audio id="sound2" src="sounds/sound2.mp3"></audio>

<button onclick="document.getElementById('sound1').play()">Sound 1</button><br />
<button onclick="document.getElementById('sound2').play()">Sound 2</button><br />

</body>
</html>

Thanks in advance.

提前致谢。

回答by Arnaud Leyder

Try something like that:

尝试这样的事情:

<audio id="sound1" src="sounds/sound1.mp3"></audio>
<audio id="sound2" src="sounds/sound2.mp3"></audio>

<button onclick="playSound1()">Sound 1</button><br />
<button onclick="playSound2()">Sound 2</button><br />

<script type="text/javascript">
var audio1 = document.getElementById('sound1');
var audio2 = document.getElementById('sound2');
function playSound1(){
if (audio1.paused !== true){
    audio1.pause();
    audio2.play();
    }
else{
    audio2.play();
    }
}
function playSound2(){
if (audio2.paused !== true){
    audio2.pause();
    audio1.play();
    }
else{
    audio1.play();
    }
}
</script>

Though I would advice you use the addEventListenermethod on the button tag rather than the onclick attribute as it is more maintainable.

虽然我建议您在按钮标签上使用addEventListener方法而不是 onclick 属性,因为它更易于维护。

Thanks

谢谢

回答by Walt Impellicceiri

Put the id of the corresponding audio into a data-target attribute on a button. On load, get the buttons and assign a click handler that Reloads the current Audio, sets the current Audio element to the button's target, and plays the current Audio

将相应音频的 id 放入按钮上的 data-target 属性中。加载时,获取按钮并分配一个单击处理程序,该处理程序重新加载当前音频,将当前音频元素设置为按钮的目标,并播放当前音频