Categories
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('https://file-examples-com.github.io/uploads/2017/11/file_example_OOG_1MG.ogg');
myAudio.addEventListener('ended', () => {
  myAudio.currentTime = 0;
  myAudio.play();
});
myAudio.play();

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.