简体   繁体   English

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

[英]Javascript play sound on click, second button click stop first sound

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. 提前致谢。

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 addEventListener method on the button tag rather than the onclick attribute as it is more maintainable. 尽管我建议您在按钮标签上使用addEventListener方法,而不是onclick属性,因为它更易于维护。

Thanks 谢谢

Put the id of the corresponding audio into a data-target attribute on a button. 将相应音频的ID放在按钮上的data-target属性中。 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 加载时,获取按钮并分配一个单击处理程序,以重新加载当前音频,将当前Audio元素设置为按钮的目标,并播放当前Audio

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM