Gav
Gav

Reputation: 37

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.

Upvotes: 1

Views: 14664

Answers (2)

Arnaud Leyder
Arnaud Leyder

Reputation: 7002

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

Upvotes: 4

Walt Impellicceiri
Walt Impellicceiri

Reputation: 21

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

Upvotes: 0

Related Questions