使用原生video实现直播


video标签是不能直接使用直播流的来播放的,需要使用hls转码过后才能播放

hls.js是一个可以实现HTTP实时流媒体客户端的js库,依赖于video标签和Media Source ExtensionsAPI,它的工作原理是将MPEG2传输流和AAC/MP3流转换成ISO BMFF (MP4)片段

优点: 原生开发引用的包比较少且体积小,很纯净,可以自定义UI和功能,更专注于HLS协议流,只支持HLS
缺点: 如果对UI要求高的话实现起来比较繁琐,功能上也需要自己调API实现

安装

CDN:
  

NPM:
npm install hls.js --save

使用

// html



// js
methods: {
	initVideo(){
      let _this = this;
      _this.$nextTick(() => {
        _this.videoPlayer = _this.$refs.video-player;
        console.log(_this.videoPlayer);
        if(Hls.isSupported()) {
          let hls = new Hls();
          hls.loadSource('https://live.cgtn.com/1000/prog_index.m3u8'); // 直播流地址
          hls.attachMedia(video);
          hls.on(Hls.Events.MANIFEST_PARSED,function() {
            // 成功
            _this.videoPlayer.play();
          });
           hls.on(Hls.Events.ERROR, (event, data) => {
            // 失败
            console.log(event, data)
          });
        }
      });
    },
}