我正在开发一个登陆页面,需要在视频滚动到视图中时使元素自动播放声音。
浏览器对此非常严格(这是可以理解的,因为它会破坏用户体验)。我遇到的一些解决方法是:
出于视觉考虑,第一个不是一个选项。另外两个显然可以在 Chrome/Firefox 中使用,但不能在 Safari 上使用,因为 Safari 会阻止视频。
有什么方法可以在 Safari 中自动播放有声视频吗?
截至 2022 年 1 月我的最后一次知识更新,由于为了获得更好的用户体验而进行的浏览器限制,在 Safari 上自动播放有声视频可能具有挑战性。 Apple 的政策通常要求用户交互才能自动播放声音。
您可以考虑尝试以下方法:
- 包括视频控制:
在视频元素上提供控件,因为如果存在控件,某些浏览器可能允许自动播放。但是,这对于您的目标网页来说可能在视觉上不有吸引力。
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>
请注意,浏览器更新可能会改变自动播放策略的工作方式,因此最好检查最新信息和浏览器版本。