Javascript HTML5视频事件无法在Safari上触发

时间:2018-04-26 20:51:04

标签: javascript safari html5-video

我有一个包含Javascript的HTML页面,用于在任何浏览器上使用HTTP Live Streaming播放视频(实际上只是这种情况下的音频内容)。在大多数情况下,它使用hls.js但是,对于Apple产品,我需要采取不同的方式,因为Safari具有本机HLS支持。

完整页面如下所示,但重要的是这些:

else if (video.canPlayType('application/vnd.apple.mpegurl')) {
    video.src = 'music.m3u8';
    video.addEventListener('canplay', startPlaying);
    //document.addEventListener('DOMContentLoaded', startPlaying);
}

canplay事件触发startPlaying()事件被调用时,会发生一个按钮,用户可以按此按钮开始播放视频。但是,在我朋友的iPhone 8plus(iOS 11.3.1)上,这并不起作用:没有任何按钮可见。相反,如果我注释掉video.addEventListener()行并将其替换为document.addEventListener()行,那么一切正常:按钮可见,他可以播放流。

有人能发现我做错了什么吗?可能是一个古怪的错误,因为我对这个网络/脚本的东西不是很有经验,给我鼻子流血......当然,我可以把它留给DOM加载方法,但它不是对,,我宁愿做对。

<!DOCTYPE html PUBLIC "-//Netscape Comm. Corp.//DTD HTML//EN">
<html>
<script src="hls.js/dist/hls.js"></script>

<head><meta http-equiv="content-type" content="text/html; charset=UTF-8"></head>
<body>
<video id="video"></video>
<button id="play" hidden>Loading</button>
<script>
'use strict';
var video = document.getElementById('video');
var playButton = document.getElementById('play');

function startPlaying() {
    // For mobile browsers the start of playing has to
    // be performed by a user action otherwise it will
    // be ignored
    playButton.addEventListener('click', function() {
        video.play();
        video.muted = false;
        video.volume = 1;
        playButton.innerHTML = "Playing";
    });
    playButton.hidden = false;
    playButton.innerHTML = "Ready to play";
}

if (Hls.isSupported()) {
    var hls = new Hls();
    hls.loadSource('music.m3u8');
    hls.attachMedia(video);
    hls.on(Hls.Events.MANIFEST_PARSED, startPlaying);
}
// hls.js is not supported on platforms that do not have Media Source Extensions (MSE) enabled.
// When the browser has built-in HLS support (check using `canPlayType`), we can provide an HLS manifest (i.e. .m3u8 URL) directly to the video element through the `src` property.
// This is using the built-in support of the plain video element, without using hls.js.
else if (video.canPlayType('application/vnd.apple.mpegurl')) {
    video.src = 'music.m3u8';
    video.addEventListener('canplay', startPlaying);
    //document.addEventListener('DOMContentLoaded', startPlaying);
}
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

通过other question中的调查,解决方法是等待事件loadedmetadata,所以在我的案例中video.addEventListener('loadedmetadata', startPlaying),因为这是您要去的最后一个事件从Safari上的HTML5视频元素获取,除非您在用户控制的白名单中。确认这适用于iOS 11.3.1。