gnosis23 / hello-world-blog

还是 issues 里面写文章方便
https://bohao.work
0 stars 0 forks source link

浏览器自动播放 #111

Open gnosis23 opened 2 years ago

gnosis23 commented 2 years ago

现代浏览器为了防止恶意骚扰,当用户没有互动(点击、触摸等)前,不能直接播放(声音)视频。 但是也有额外的方式来允许直接播放,各家浏览器不一样。

Chrome 66+

参考链接:https://developer.chrome.com/blog/autoplay/

Chrome的自动播放策略:

Media Engagement Index

这个分数和用户观看时间、声音、屏幕大小有关;可以在 about://media-engagement 查看

实测分数超过 0.3 就能自动播放了。 sss

Safari

搜到篇关于自动播放的文章:https://webkit.org/blog/7734/auto-play-policy-changes-for-macos/

Safari in macOS High Sierra uses an automatic inference engine to block media elements with sound from auto-playing by default on most websites. Safari 11 also gives users control over which websites are allowed to auto-play video and audio by opening Safari’s new “Websites” preferences pane, or through the “Settings for This Website…” option in the Safari menu.

和 Firefox 相似都有个选项可以直接调整自动播放的行为。

截屏2022-05-25 21 35 07

看看B站直播在禁用自动播放有声音的视频以后:

截屏2022-05-25 21 36 46

最佳实践

捕获 play 抛出的 promise:

var promise = document.querySelector('video').play();

if (promise !== undefined) {
    promise.catch(error => {
        // Auto-play was prevented
        // Show a UI element to let the user manually start playback
    }).then(() => {
        // Auto-play started
    });
}