HLS(HTTP Live Streaming) 把整个流分成一个个小的基于 HTTP 的文件来下载,每次只下载一些。HLS 协议由三部分组成:HTTP、M3U8、TS。这三部分中,HTTP 是传输协议,M3U8 是索引文件,TS 是音视频的媒体信息。
HLS 是提供一个 m3u8 地址,Apple 的 Safari 浏览器直接就能打开 m3u8 地址,譬如:
http://demo.srs.com/live/livestream.m3u8
Android 不能直接打开,需要使用 html5 的 video 标签,然后在浏览器中打开这个页面即可,譬如:
<video width="640" height="360"
autoplay controls autobuffer
src="http://demo.srs.com/live/livestream.m3u8"
type="application/vnd.apple.mpegurl">
</video>
协议解析内容参考地址:https://www.cnblogs.com/jimodetiantang/p/9133564.html
hls在项目中的实际开发应用案例(仅供参考)
vue安装依赖 npm install hls.js --save
//点击按钮,打开弹框,显示视频窗口
videoOpen(videoId){
this.videoShow = true;//打开弹框
this.videoId = videoId;//后台提供的设备的id
this.videoPlay();
},
//视频播放
videoPlay(){
var that = this;
//使用videoId请求播放的路径
videoPlayRequest({"deviceId":this.videoId}).then(res=>{
//获得要播放的video引用,相当于documentById.getElementById('');
var video = that.$refs.video;
//var videoSrc = 'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8';
var videoSrc = res.body;
//是否支持hls,hls.js源码中封装好的
if (Hls.isSupported()) {
that.hls = new Hls();
//传视频路径
that.hls.loadSource(videoSrc);
//传元素索引
that.hls.attachMedia(video);
that.hls.on(Hls.Events.MANIFEST_PARSED, function() {
video.play();
//后台需要前端,进行心跳监测,每隔一分钟传一次id,这个看自己的情况是否需要吧
that.liveTimer = setInterval(function(){
that.videoLive();
},60000);
});
};
});
},
//视频关闭
videoPause(){
this.videoShow = false;
if (this.hls) {
//清除心跳检测定时器
clearInterval(this.liveTimer);
this.liveTimer = '';
this.$refs.video.pause();
//销毁视频流通道
this.hls.destroy();
this.hls = null;
//调用关闭流的接口
videoStopRequest({"deviceId":this.videoId}).then(res=>{
});
};
},
//视频停止
videoLive(){
//调用停止流的接口
videoLiveRequest({"deviceId":this.videoId}).then(res=>{
});
},