我知道有类似的主题,但它们要么已经过时,要么答案是 JAVA 代码。
Android 似乎不再允许自动播放,而是需要用户手势。不过,我想确保在停止尝试之前用尽所有(合理的)选项。
播放在 iOS 和桌面上完美运行。
现在有什么办法可以在安卓设备上自动播放吗?
视频标签
<video
muted="true"
playsinline="true"
loop="true"
class="bg-video"
autoplay="true"
>
<source
src="videos/low-android-480.mp4"
class="bg-video-source"
type="video/mp4" // Tried also without specifying the type
/>
</video>
– 破解以尝试发送用户手势(不起作用)
const event = new MouseEvent("touchstart", {
view: window,
bubbles: true,
cancelable: true,
});
window.addEventListener("touchstart", function videoStart() {
videoElement.play();
// remove from the window and call the function we are removing
window.removeEventListener("touchstart", videoStart);
});
...
if (videoElement.paused) {
window.dispatchEvent(event);
}
– 只需调用 videoElement.play();
(不起作用)
更新 #1
像这样修改时的 hack 示例 dispatchEvent 部分
window.setTimeout(() => {
window.dispatchEvent(event);
});
让视频在 Android Chrome 浏览器上播放。但是,不在 native 浏览器上。仍在为那个问题寻找解决方案...
更新 #2
这是 Jordi Castilla 的回答中提到的文章中的一个有用 fragment 。它让我发现实际的 videoElement.play()
promise 在 Android Native 浏览器上被拒绝了。
const promise = videoElement.play();
if (promise !== undefined) {
promise.then(_ => {
// Autoplay started!
alert("started autoplay");
}).catch(error => {
// Autoplay was prevented.
alert("failed autoplay");
// Show a "Play" button so that user can start playback.
});
}
最佳答案
好的,因为没有其他人在回答,对于有类似斗争的人来说,判决是这样的:
- 您无法在 Android 原生浏览器上自动播放视频
- 您无法在 iOS 9.x 及更低版本上自动播放视频
不过,对于 Android Chrome 浏览器,UPDATE #1 应该是关于如何在其中进行自动播放的指南。
编码愉快!
注意我希望有人在这里证明我错了
关于javascript - 在 Android 上自动播放 HTML5 视频 (JS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47989961/