Automatically play Audio object in javascript

Viewed 1321

I have created a audio object with new Audio().

const audio = new Audio()

I know, to play a audio user interaction is mandatory. So I tried with the following code.

audio.addEventListener("canplaythrough", () => {
   audio.play()
});

But it throws the Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first error again. How to solve this?

2 Answers

As @Unmitigated mentioned in the comment, user interaction is mandatory to play an audio. If you want to play the user interaction, modify the code as below

audio.addEventListener("canplaythrough", () => {
   audio.play().catch(e => {
      window.addEventListener('click', () => {
         audio.play()
      })
   })
});

Edited Add { once: true } to trigger only once.

audio.addEventListener("canplaythrough", () => {
   audio.play().catch(e => {
      window.addEventListener('click', () => {
         audio.play()
      }, { once: true })
   })
});

In order to be allowed to autoplay, either the user needs to have interacted with the page or the audio/video needs to be muted.

You can try:

let audio = new Audio('a_file');

audio.muted = true;
audio.addEventListener("canplaythrough", () => {
   audio.play()
});
Related