monie
monie

Reputation: 63

how do I stop playing audio using the same button

My code plays an audio when the button is clicked but It does not pause when I click it again.

I want to use the same button to play and pause the audio using js.

const rollSound = new Audio

("sounds/short-guided-meditation.ogg");
document.getElementById('play').addEventListener("click", e => rollSound.play());

any help would be highly appreciated.

Edit: I still need an answer. Please share your knowledge.

Upvotes: 1

Views: 178

Answers (1)

Jax-p
Jax-p

Reputation: 8551

As is described at MDN HTMLMediaElement documentation, you can check whether is Media element .paused and decide if you would like to play() or stop(). Something like this:

document.getElementById('play').addEventListener("click", e => rollSound.paused ? rollSound.play() : rollSound.pause());

Snippet example:

const rollSound = document.getElementById('rollSound');
const btn = document.getElementById('play');

btn.addEventListener("click", e => rollSound.paused ? rollSound.play() : rollSound.pause());
<audio id=rollSound loop>
  <source src="https://actions.google.com/sounds/v1/alarms/digital_watch_alarm_long.ogg" type="audio/ogg">
</audio>
<button id=play>play/stop</button>

Upvotes: 2

Related Questions