我有一个简单的网页,其中包含多个 <video>
轮播中不同幻灯片中的元素。当视频位于轮播中的事件幻灯片时,我是 .play()
观看视频并 .pause()
荷兰所有其他人。我希望视频在静音状态下自动播放,并且完全了解每个浏览器的自动播放策略,但是即使用户与网页进行交互(通过暂停/播放/取消静音第一个播放的视频),任何后续视频都不会播放由于错误而静音:
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 和桌面浏览器按预期工作。
- 在我播放并取消静音每个视频后,当重新访问该视频时,它将在静音状态下正常播放
最佳答案
问题是我们在 touchmove
之后监听 touchend
事件,这是滑动时注册的手势。但这并未注册为允许在 iOS 上自动播放的用户手势。
应该允许自动播放的用户手势在 spec 中定义。 。通过测试,我发现唯一允许自动播放的用户手势包括click
、pointerup
和mouseup
。 touchend
也可以在 click
后触发,但在 touchmove
后触发。
了解如何正确处理用户手势也很重要,如 defined by the Safari team :
A note about the user gesture requirement: when we say that an action must have happened “as a result of a user gesture”, we mean that the JavaScript which resulted in the call to video.play(), for example, must have directly resulted from a handler for a touchend, click, doubleclick, or keydown event. So, button.addEventListener('click', () => { video.play(); }) would satisfy the user gesture requirement. video.addEventListener('canplaythrough', () => { video.play(); }) would not.
关于javascript - 用户手势后视频不会自动播放音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74145147/