【发布时间】:2017-12-27 09:55:17
【问题描述】:
我知道有类似的主题,但是它们要么已经过时,要么带有 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 浏览器上播放。但是,不在本机浏览器上。仍在为那个寻找解决方案......
更新 #2
这是 Jordi Castilla 的回答中提到的文章中的一个有用的 sn-p。它让我发现实际的 videoElement.play() 承诺在 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.
});
}
【问题讨论】:
标签: javascript android html