【问题标题】:Play/Pause video with sound on intersection - Chrome - DOMException: play() failed because the user didn't interact with the document first在交叉路口播放/暂停有声音的视频 - Chrome - DOMException:play() 失败,因为用户没有先与文档交互
【发布时间】:2020-06-08 23:42:48
【问题描述】:

我想在用户视口与视频相交时播放视频,或者在视频离开视图后暂停视频。我设法在 Firefox 上做到了,但 Chrome 似乎有一些问题。

我得到的是控制台中的错误:

Uncaught (in promise) DOMException: play() failed 因为用户 没有先与文档进行交互。

我用谷歌搜索了一下,发现有一个使用 muted="muted" 自动播放视频的问题。这行得通,但我也需要声音。

我尝试以编程方式取消视频静音,但它不起作用。 此外,我尝试触发事件和其他事情,希望它能起到作用,即创建误报用户交互,但没有运气。

我在问自己,YouTube 如何实现声音自动播放(在任何用户交互之前)?

代码如下:

var onIntersection = function(entries, observer){
    entries.forEach(function(entry){
        if( entry.isIntersecting && entry.intersectionRatio >= 0.5){
            entry.target.play();
        }else{
            entry.target.pause();
        }
    });
};

if( 'IntersectionObserver' in window ){

    var observerOptions = {
        threshold: [0, 0.5]
    };

    var observer = new IntersectionObserver(onIntersection, observerOptions);

    $('video').each(function(){
        observer.observe($(this)[0]);
    });
}

HTML:

<video inline playsinline autoplay loop style>
    <source src="..." type="video/mp4">
</video>

【问题讨论】:

    标签: javascript video intersection-observer


    【解决方案1】:

    chrome 可以防止浏览器中的任何垃圾邮件。只需在您的 attr 视频中添加此 $(body).trigger('click')muted="true" 即可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-09
      • 2020-05-02
      • 2020-12-25
      • 1970-01-01
      • 1970-01-01
      • 2018-09-30
      相关资源
      最近更新 更多