Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I would play an audio file (on loop) after I open my website.
I know browsers have restrictions about autoplay, but is it possible to autoplay any audio using JavaScript?
Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
480 views
Welcome To Ask or Share your Answers For Others

1 Answer

There currently isn't any guaranteed way; MDN has the following general guidance:

As a general rule, you can assume that media will be allowed to autoplay only if at least one of the following is true:

  • The audio is muted or its volume is set to 0
  • The user has interacted with the site (by clicking, tapping, pressing keys, etc.)
  • If the site has been whitelisted; this may happen either automatically if the browser determines that the user engages with media frequently, or manually through preferences or other user interface features
  • If the autoplay feature policy is used to grant autoplay support to an and its document. Otherwise, the playback will likely be blocked. The exact situations that result in blocking, and the specifics of how sites become whitelisted vary from browser to browser, but the above are good guidelines to go by.

Current policies of Chrome and Safari are that you can not just play audio once the page has loaded (unless it's muted).

Chrome has the following policies:

  • Muted autoplay is always allowed.
  • Autoplay with sound is allowed if:
  • User has interacted with the domain (click, tap, etc.).
  • On desktop, the user's Media Engagement Index threshold has been crossed, meaning the user has previously played video with sound.
  • The user has added the site to their home screen on mobile or installed the PWA on desktop.
  • Top frames can delegate autoplay permission to their iframes to allow autoplay with sound.

Safari has the following guidance regarding autoplay:

  • Websites should assume any use of or requires a user gesture click to play.
  • It’s important to detect if auto-play was denied, since users now have the ability to turn off all forms of auto-play, including silent videos.
  • Auto-play restrictions are granted on a per-element basis.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...