您可以在 Safari 中自动播放有声视频吗?

问题描述 投票:0回答:1

我正在开发一个登陆页面,需要在视频滚动到视图中时使元素自动播放声音。

浏览器对此非常严格(这是可以理解的,因为它会破坏用户体验)。我遇到的一些解决方法是:

  • 包括视频控制;
  • 检查用户交互(点击、按键等);
  • 检查用户是否已从同域的其他页面重定向。

出于视觉考虑,第一个不是一个选项。另外两个显然可以在 Chrome/Firefox 中使用,但不能在 Safari 上使用,因为 Safari 会阻止视频。

有什么方法可以在 Safari 中自动播放有声视频吗?

javascript html html5-video autoplay
1个回答
0
投票

截至 2022 年 1 月我的最后一次知识更新,由于为了获得更好的用户体验而进行的浏览器限制,在 Safari 上自动播放有声视频可能具有挑战性。 Apple 的政策通常要求用户交互才能自动播放声音。

您可以考虑尝试以下方法:

  1. 包括视频控制:

在视频元素上提供控件,因为如果存在控件,某些浏览器可能允许自动播放。但是,这对于您的目标网页来说可能在视觉上不有吸引力。

document.addEventListener("DOMContentLoaded", function() {
  var video = document.getElementById("yourVideoElementId");

  // Check if the document has received user interaction
  document.addEventListener("click", function() {
    // Play the video
    video.play();
  });

  // Additional checks for Safari
  document.addEventListener("scroll", function() {
    // Check if video is in view
    if (isElementInViewport(video)) {
      // Play the video
      video.play();
    }
  });

  // Function to check if an element is in the viewport
  function isElementInViewport(el) {
    var rect = el.getBoundingClientRect();
    return (
      rect.top >= 0 &&
      rect.left >= 0 &&
      rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
      rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
  }
});
<video controls autoplay>
  <source src="your_video.mp4" type="video/mp4">
  Your browser does not support the video tag.
</video>

<button onclick="playVideo()">Play Video</button>
<video id="myVideo" src="your_video.mp4" type="video/mp4"></video>

<script>
  function playVideo() {
    var video = document.getElementById("myVideo");
    video.play();
  }
</script>

请注意,浏览器更新可能会改变自动播放策略的工作方式,因此最好检查最新信息和浏览器版本。

© www.soinside.com 2019 - 2024. All rights reserved.