How to check if the audio element is playing with JavaScript?

Spread the love

Sometimes, we want to check if the audio element is playing with JavaScript.

In this article, we’ll look at how to check if the audio element is playing with JavaScript.

How to check if the audio element is playing with JavaScript?

To check if the audio element is playing with JavaScript, we check the duration and paused properties.

For instance, we write

const myAudio = document.getElementById("myAudioID");

if (myAudio.duration > 0 && !myAudio.paused) {
  //...
} else {
  //...
}

to get the audio element with getElementById.

And we check if the audio is playing with myAudio.duration > 0 && !myAudio.paused.

It’s playing if paused is false and has a non-zero duration.

Conclusion

To check if the audio element is playing with JavaScript, we check the duration and paused properties.

Leave a Reply

Your email address will not be published. Required fields are marked *