最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Automatically play Audio object in javascript - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question edited Jul 30, 2021 at 17:07 Dev elon asked Jul 30, 2021 at 16:59 Dev elonDev elon 631 gold badge1 silver badge6 bronze badges 3
  • 1 You can only call play after user interaction, e.g. a click. – Unmitigated Commented Jul 30, 2021 at 17:01
  • Browsers don't let you auto-play audio/video without the user interacting with the page. This is to prevent things like ads, though there is a workaround that should work. On your <audio> element, try adding autoplay and muted. Something like <audio autoplay muted src=""></audio>. See: developer.mozilla/en-US/docs/Web/Media/… – gen_Eric Commented Jul 30, 2021 at 17:03
  • Yeah, I know window need a user interaction. That's why added 'canplaythrough' event listener. I need to play the audio as soon as possible. In my case, this is not a dom audio element. and I don't thing there is a way to add muted attribute to audio object. – Dev elon Commented Jul 30, 2021 at 17:10
Add a ment  | 

2 Answers 2

Reset to default 3

As @Unmitigated mentioned in the ment, 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()
});
发布评论

评论列表(0)

  1. 暂无评论