Skip to content

前端页面播放流媒体 #24

@Dream4ever

Description

@Dream4ever

需求描述

为了实现流媒体播放的效果,不仅需要用 FFmpeg 把视频切割成 ts 文件和对应的 m3u8 播放列表,前端还需要用 hls.js 这个库来播放。这个库的兼容性比 video.js 好很多,PC 和移动端都不报错;video.js 总是在页面第一次刷新出来的时候报错,再刷新一下才能播放视频。

方案调研

调研过程

暂无

入选方案

以列表形式记录入选的方案。

应用过程

vue-cli 集成

vue-cli 中引入 hls.js 的正确姿势:

import hlsjs from 'hls.js';
...
window.Hls = hlsjs;

实际调用

在前端页面中的实际调用代码,使用 hls.js 官方文档提供的代码 即可:

<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
<video id="video"></video>
<script>
  var video = document.getElementById('video');
  if(Hls.isSupported()) {
    var hls = new Hls();
    hls.loadSource('https://video-dev.github.io/streams/x36xhzz/x36xhzz.m3u8');
    hls.attachMedia(video);
    hls.on(Hls.Events.MANIFEST_PARSED,function() {
      video.play();
  });
 }
  else if (video.canPlayType('application/vnd.apple.mpegurl')) {
    video.src = 'https://video-dev.github.io/streams/x36xhzz/x36xhzz.m3u8';
    video.addEventListener('loadedmetadata',function() {
      video.play();
    });
  }
</script>

错误排查 1

有时候控制台会报下面的错误:

Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause()

上网查了一下,是 play()pause() 这两个方法之间起了冲突。解决方法在这里:How to prevent “The play() request was interrupted by a call to pause()” error?

关键代码:

var isPlaying = video.currentTime > 0 && !video.paused && !video.ended 
    && video.readyState > 2;

if (!isPlaying) {
  video.play();
}

错误排查 2

控制台又会报下面的错误:

Uncaught DOMException: Failed to read the 'buffered' property from 'SourceBuffer': This SourceBuffer has been removed from the parent media source.
    at e.onSBUpdateEnd

查看报错的地方,是 hls.js,查看对应的 m3u8ts,都是可以在浏览器中直接正常访问的,说明是别的地方的问题。

后来经过排查,发现是视频本身的问题,用格式工厂先预处理一下,然后再用 FFmpeg 切片之后就没问题了。

要点总结

相关 issue:

Metadata

Metadata

Assignees

No one assigned

    Labels

    Front-endEverything you see and experienceJSJavascript

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions