简体   繁体   中英

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.

Thanks

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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