m3u8 文件是指 UTF-8 编码格式的 m3u 文件。m3u 文件是记录了一个索引纯文本文件,打开它时播放软件并不是播放它,而是根据它的索引找到对应的音视频文件的网络地址进行在线播放。

HLS 与 M3U8 HLS(全称:Http Live Streaming)是由 Apple 公司定义的用于实时流传输的协议

公司项目中使用了视频监控功能,需要在系统内显示 m3u8 格式的视频。

1、安装 hls.js 插件或者使用 CDN 引入

1
2
3
npm install hls.js --save
// 或者
<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>

2、业务代码如下:

1
2
3
4
5
6
7
8
<video
ref="video"
id="myVideo2"
class="video-js vjs-default-skin vjs-big-play-centered"
autoplay="autoplay"
controls
style="width: 100%; height: 280px; margin-top: 5px"
></video>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import Hls from "hls.js";
export default {
data() {
return {
hls: null,
};
},
methods: {
getStream(source) {
if (Hls.isSupported()) {
this.hls = new Hls();
this.hls.loadSource(source);
this.hls.attachMedia(this.$refs.video);
this.hls.on(Hls.Events.MANIFEST_PARSED, () => {
this.$refs.video.play();
});
this.hls.on(Hls.Events.ERROR, (event, data) => {
this.$message("视频加载失败");
});
}else{
this.$message("格式不支持")
}
},
},
// 从接口获取的视频资源应当写在mounted里面,否则容易出现进入视频页面的时候,视频加载不出来的现象
mounted() {
this.$service.get("demo/test").then((res) => {
this.getStream(res.data[1].hls);
});
},
};