直播流播放插件—xgplayer

🍉 xgplayer 官网:https://v3.h5player.bytedance.com/

🏠 github:https://github.com/bytedance/xgplayer/


需求

😉😉

做一个长这样的,播放ws视频,视频统一封面图,点击播放、全屏,点击查看更多查看所有视频


使用到的依赖

"xgplayer": "^2.32.2",
"xgplayer-flv": "^2.5.3",
"xgplayer-flv.js": "^2.3.0"

依赖的使用

RtspPlayer.vue

// 视频组件 RtspPlayer.vue
<template>
  <div
    class="videoContent"
    :id="elId"
  ></div>
</template>

<script>
import FlvJsPlayer from 'xgplayer-flv.js';
import { v4 } from 'uuid';  // 用来生成 id ,避免 key 重复
export default {
  name: 'CusPlayer',
  components: {},
  data() {
    return {
      player: null,  // player 对象
      elId: '',  // id
      currentIndex: null,  // 当前被点击的视频 index
    };
  },
  props: {
    clickPlay: {
      type: Boolean,
      default: false,
    },  // 父组件传来的,表示该视频的 播放按钮 被点击
    isFull: {
      type: Boolean,
      default: false,
    },  // 父组件传来的,表示该视频的 全屏按钮 被点击
    index: {
      type: Number,
    },  // 父组件传来的,表示被点击视频的 index
  },
  created() {
    this.elId = v4(); // 避免 key 重复
  },
  methods: {
    createPlayer(url, coverPage) {
      if (!url) {
        return;
      }
      let self = this;
      this.player = new FlvJsPlayer({
        id: this.elId,
        url: url,
        autoplayMuted: false,  // 静音播放
        poster: coverPage,  // 封面图
        videoInit: true,  // 没有封面图时,用第一帧
        fitVideoSize: 'auto',
        fluid: true,
        autoplay: false,  // 自动播放
        isLive: true,
        screenShot: false,
        controls: false,  // 控制条
        whitelist: [''],
        ignores: ['time'],
        customConfig: {
          isClickPlayBack: false,
        },
        flvOptionalConfig: {
          enableWorker: true,
          enableStashBuffer: false, //关闭缓存
          stashInitialSize: 2048, //缓存大小2m
          lazyLoad: false,
          lazyLoadMaxDuration: 40 * 60,
          autoCleanupSourceBuffer: true,
          autoCleanupMaxBackwardDuration: 35 * 60,
          autoCleanupMinBackwardDuration: 30 * 60,
        },
      });
      this.player.on('play', function () {
          // 为了解决 bug1
          // 打开弹窗时,如果没点击的情况下,每一个视频都暂停
        if (self.currentIndex === null) {
          self.player.pause();
        }
      });

      this.player.on('error', e => {
        console.log(e, 'eeeeeeeeeeee');
      });

      document.addEventListener('contextmenu', function (e) {
        e.preventDefault();
      });

      this.player.on('requestFullscreen', () => {});

      this.player.on('exitFullscreen', () => {
         // 让父组件把 isFull[index] 设置为 false,全屏按钮才能多次点击
        this.$emit('nowIsfullScreen', this.currentIndex);
      });
    },

    closePlayer() {
      if (this.player) {
        this.player.destroy();
        this.player = null;
      }
    },
  },

  beforeDestroy() {
    this.player.destroy();
  },

  watch: {
    index(newVal) {
      this.currentIndex = newVal;
    },
    clickPlay(newVal) {
      if (newVal) {
          // DOMException: The play() request was interrupted by a call to pause().
          // 在弹窗中,如果点击第一页的视频,但该视频播放不了,再点击第二页的视频,不 catch 会报错
        let playPromise = this.player.play();
        if (playPromise) {
          playPromise
            .then(() => {
                // 播放成功
                // 因为项目中很多视频都播放不了,父组件别把播放按钮消失
              this.$emit('videoSuccess', this.currentIndex);
            })
            .catch(() => {});
        }
      }
    },
    isFull(newVal) {
      if (newVal) {
          // 不写 this.player.root 全屏不好使
        this.player.getFullscreen(this.player.root);
      }
    },
  },
};
</script>

RealMonitor.vue

<div class="card">
    <div class="item-video">
        <div class="video">
            <CusPlayer
              :ref='`videoRef${index}`'
              :clickPlay="clickPlay[index]"
              :isFull="isFull[index]"
              :index="currentIndex"
              @nowIsfullScreen="nowIsfullScreen"
              @videoSuccess="videoSuccess"
            ></CusPlayer>
        </div>
        <div class="pause">
            <img
              v-if="!isSuccess[index]"
              src="@/assets/monitoPause.png"
              @click="pauseHandle(index)"
            >
        </div>
        <div class="mask">
            <img
              class="mask-img"
              src="@/assets/monitoMask.png"
            >
            <div class="full">
              <img
                class="full-img"
                src="@/assets/monitoFull.png"
                @click="fullScreenHandle(index)"
              >
            </div>
        </div>
    </div>
</div>

data() {
    return {
      clickPlay: [],  // 用来记录 video 被点击播放按钮
      isFull: [],  // 用来记录 video 被点击全屏按钮
      isSuccess: [],  // 用来记录 video 播放成功
      currentIndex: null,
      videoList: [{ name: '' }, { name: '' }, { name: '' }, { name: '' }],
    };
  },
  
// 向接口请求数据
async getrequests() {
      try {
      this.clickPlay = [];
      this.isFull= [];
      this.isSuccess= [];
        const res = await getMonitor();
        if (res.data.code === 200) {
          const dataList = res.data.data;
          dataList.slice(0, 4).forEach((item, index) => {
            this.clickPlay.push(false);
            this.isFull.push(false);
            this.isSuccess.push(false);
            // 调用 createVideo 方法,生成video
            this.createVideo(index, item.playerUrl, item.cover);
            this.videoList[index] = this.videoList[index] || {};
            this.videoList[index].name = item.remark;
          });
        } else {
          console.log('请求失败');
        }
      } catch (error) {
        console.log(error, '请求失败');
      }
},

// 创建video
createVideo(index, url) {
    this.$nextTick(() => {
    // 调用组件方法
        this.$refs[`videoRef${index}`][0].createPlayer(url, cover);
    });
},

// 监听 “播放” 按钮
pauseHandle(index) {
    this.currentIndex = index;
    Vue.set(this.clickPlay, index, true);
},

// 监听 “全屏” 按钮
fullScreenHandle(index) {
    this.currentIndex = index;
    Vue.set(this.isFull, index, true);
},

// 监听 退出全屏
nowIsfullScreen(index) {
    Vue.set(this.isFull, index, false);
},

// 视频播放成功
videoSuccess(index) {
    Vue.set(this.isSuccess, index, true);
},

⭐️ 弹窗中同理,没有什么特殊的


Bug

弹窗中视频自动播放

👾👾

在主页面(父组件)上的视频,不会自动播放

在弹窗中的视频,设置了 autoplay = false ,也会自动播放

在视频组件中监听 play 事件

如果视频播放了,且没有点击过任何视频,即 currentIndex = null

就将该视频暂停

DOMException: The play() request was interrupted by a call to pause().

👾👾

在弹窗中,如果点击第一页的视频,如果该视频播放不了

再点击第二页的视频,会报错

play() 的返回值是 promise 对象,catch 一下

鼠标右键失效

👾👾

将接口请求 try catch 一下

<think>好的,用户想在UniApp中集成XGPlayer播放HLS格式的视频流,实现视频监控功能。我需要先回顾一下相关的引用内容,看看有没有可用的信息。 首先,引用[1]和[2]提到了在Vue项目中使用xgplayer-hls.js的方法,包括引入插件和初始化播放器。但UniApp虽然基于Vue,可能有不同的环境,比如H5和小程序,需要确认是否支持。用户可能需要针对H5环境进行配置,因为小程序可能有视频组件的限制。 引用[3]提到HLS加密视频的清晰度问题,可能需要设置合适的分辨率和码率,这对视频监控很重要,但用户当前的问题主要是集成播放,可能后续需要考虑优化。 接下来,我需要考虑UniApp中的具体实现步骤。UniApp的H5环境可以使用Web端的XGPlayer,但需要安装相关依赖。可能需要使用npm安装xgplayerxgplayer-hls插件,然后在页面中引入。此外,要确保视频流的地址正确,并且跨域问题已解决。 另外,需要注意UniApp的页面生命周期,比如onReady时初始化播放器,避免DOM未加载完成。对于视频监控,可能需要自动播放和循环播放的设置,同时处理可能的错误,比如网络问题或格式不支持。 用户可能遇到的常见问题包括插件未正确引入、HLS流无法播放、跨域问题等,需要提供相应的解决建议。比如检查控制台报错,使用HTTPS,或者联系后端处理CORS。 最后,生成相关问题,帮助用户进一步优化和解决问题,比如性能优化、全屏播放、不同平台适配等。</think>### UniApp集成XGPlayer播放HLS视频流步骤 #### 一、环境准备 1. 安装依赖 ```bash npm install xgplayer xgplayer-hls --save ``` 2. 创建`xgplayer-hls`自定义组件(需兼容UniApp的H5环境) #### 二、核心实现代码 ```vue <template> <view> <div id="mse"></div> </view> </template> <script> import Player from 'xgplayer' import 'xgplayer-hls' // 加载HLS插件 export default { mounted() { this.initPlayer('https://example.com/live/stream.m3u8') }, methods: { initPlayer(url) { new Player({ id: 'mse', url, isLive: true, // 启用直播模式 autoplay: true, volume: 0, fluid: true, ignores: ['progress','time','playbackRate'], hls: { retryCount: 3, // 网络错误重试次数 loadTimeout: 5000 } }) } } } </script> ``` #### 三、关键配置说明 1. **直播模式**:`isLive:true` 禁用进度条等非必要控件 2. **分辨率适配**:建议设置`fluid:true`实现容器自适应 3. **错误处理**:通过`error`事件监听播放异常 ```javascript player.on('error', (e) => { console.error('播放错误:', e) }) ``` #### 四、监控场景优化建议 1. **低延迟配置**: ```javascript hls: { liveSyncDuration: 3 // 设置3秒延迟缓冲 } ``` 2. **自动重连**: ```javascript player.on('error', () => { setTimeout(() => player.reload(), 3000) }) ``` #### 五、常见问题排查 1. **插件未生效**:确认已正确导入`xgplayer-hls`[^2] 2. **跨域问题**:确保视频流服务器配置CORS头 3. **清晰度问题**:检查视频源是否满足推荐码率(参考表1推荐参数)[^3]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值