JavaScript Answers

How to Play Looping Audio with the HTML5 Audio Element and JavaScript?

Spread the love

To play looping audio with the HTML5 audio element and JavaScript, we can listen for the ended event and call play on the audio element in event handler for the ended event.

For instance, we can write:

const myAudio = new Audio('');
myAudio.addEventListener('ended', () => {
  myAudio.currentTime = 0;;

We create the HTML audio element with the Audio constructor and the URL of the audio clip.

Then we listen to the ended event by calling addEventListener on it.

In the event handler callback, we set the currentTime back to 0 and call play to restart the same clip.

Then we call play after that to start playing the audio clip for the first time.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.