【问题标题】:Videos do not autoplay with audio after user gesture用户手势后视频不会自动播放音频
【发布时间】:2022-11-10 00:36:59
【问题描述】:

我有一个简单的网页,在轮播中的不同幻灯片中有多个 <video> 元素。当视频在轮播中的活动幻灯片中时,我.play()ing 视频和.pause()ing 所有其他人。我希望视频在静音状态下自动播放,并且完全了解每个浏览器的自动播放策略,但是即使在用户与网页交互之后(通过暂停/播放/取消静音播放的第一个视频),任何后续视频都不会播放由于错误而静音:

The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.

在用户与页面交互后,使视频静音播放的正确方法是什么?

我创建了一个codesandbox to reproduce the issue

      var vid1 = document.getElementById("video1");
      var vid2 = document.getElementById("video2");
      var vid3 = document.getElementById("video3");

      carousel.on("slideChange", function () {
        vid1.currentTime = 0;
        vid2.currentTime = 0;
        vid3.currentTime = 0;
        vid1.pause();
        vid2.pause();
        vid3.pause();

        if (carousel.activeIndex === 0) {
          var currentVideo = vid1;
          var prevVideo = vid3;
        } else if (carousel.activeIndex === 1) {
          var currentVideo = vid2;
          var prevVideo = vid1;
        } else {
          var currentVideo = vid3;
          var prevVideo = vid2;
        }

        currentVideo.volume = 1;
        currentVideo
          .play()
          .catch((e) => {
            console.error(`Error playing: ${e.message}`);
            currentVideo.muted = true;
            return currentVideo
              .play()
              .catch((err) => console.error("Error caught again", err.message));
          })
      });

一些额外的观察:

  • 这仅在 iOS 上发生。 Android 和桌面浏览器按预期工作。
  • 在我播放并取消静音每个视频后,当重新访问该视频时,它将正常播放静音

【问题讨论】:

    标签: javascript video mobile-safari swiper.js autoplay


    【解决方案1】:

    问题是我们在touchmove 之后监听touchend 事件,这是滑动时注册的手势。但这并未注册为允许在 iOS 上自动播放的用户手势。

    用户手势应该允许自动播放在spec 中定义。通过我的测试,我发现唯一允许自动播放的用户手势包括clickpointerupmouseuptouchendclick 之后触发时也有效,但在touchmove 之后无效。

    了解如何正确处理用户手势也很重要,如defined by the Safari team

    关于用户手势要求的注释:当我们说一个动作必须“作为用户手势的结果”发生时,我们的意思是导致调用 video.play() 的 JavaScript,例如,必须直接由 touchend、click、doubleclick 或 keydown 事件的处理程序产生。因此, button.addEventListener('click', () => { video.play(); }) 将满足用户手势要求。 video.addEventListener('canplaythrough', () => { video.play(); }) 不会。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-24
      相关资源
      最近更新 更多