Bootstrap

vue项目使用mpegts.js实现摄影头实时预览

安装

npm install mpegts.js

html创建视频标签

 <video style="height:500px;width:100%" id="videoElement" ref="videoElement"  controls autoplay>
      </video>

引入

import mpegts from "mpegts.js";

初始化方法

mpegtsJs () {
      if (mpegts.getFeatureList().mseLivePlayback) {
        var videoElement = this.$refs.videoElement
        if (typeof this.flvPlayer !== "undefined") {
          if (this.flvPlayer != null) {
            this.flvPlayer.unload();
            this.flvPlayer.detachMediaElement();
            this.flvPlayer.destroy();
            this.flvPlayer = null;
          }
        }
        var flvPlayer = mpegts.createPlayer({
          type: 'flv',
          isLive: true,
          url: this.dialogData.data.wsUrl,//后端返回的视频流链接
          hasAudio: false,
          hasVideo: true,
        }, {
          isLive: true,
          enableWorker: false,
          lazyLoadMaxDuration: 3 * 60,
          seekType: 'range',
          // liveBufferLatencyChasing: true,
          withCredentials: true,
          // 关闭IO隐藏缓冲区
          enableStashBuffer: false,
          // 自动清除缓存
          autoCleanupSourceBuffer: true,
          responseType: "blob",
          // 是否开启自适应码率
          enableAutoQuality: false,
          // 检测到错误时是否自动重试
          autoReloadOnError: true,
          // 预加载的分片数量,单位为个,默认值为 3 个
          segmentStartFetchNum: 3,
        });
        flvPlayer.attachMediaElement(videoElement);
        flvPlayer.load();
        flvPlayer.on(mpegts.Events.METADATA_ARRIVED, () => {
          // console.log('视频加载完成1')
          this.flvPlayer.play();
        })
        // 监听错误事件
        flvPlayer.on(mpegts.Events.ERROR, (err, errdet) => {
          // 参数 err 是一级异常,errdet 是二级异常
          if (err == mpegts.ErrorTypes.MEDIA_ERROR) {
            console.log('媒体错误')
            if (errdet == mpegts.ErrorDetails.MEDIA_FORMAT_UNSUPPORTED) {
              console.log('媒体格式不支持')
               this.mpegtsJs()
            }
          }
          if (err == mpegts.ErrorTypes.NETWORK_ERROR) {
            console.log('网络错误')
            if (errdet == mpegts.ErrorDetails.NETWORK_STATUS_CODE_INVALID) {
              console.log('http状态码异常')
            }
          }
          if (err == mpegts.ErrorTypes.OTHER_ERROR) {
            console.log('其他异常:', errdet)
          }
        })
        this.flvPlayer = flvPlayer
      }
    },

;