vue2.0上video视频切换(二)m3u8格式的

 Vue 2.0 中,如果你想要切换 video 元素的源(src),你需要确保每次切换时都提供一个不同的 src 值,以避免浏览器从缓存中加载旧的视频。

我这里使用v-if和key结合,当你使用 key 属性时,Vue 会跟踪每个节点的身份,而不仅仅是它的内容。如果 key 发生变化,Vue 会认为这是一个新的节点,因此会销毁旧的节点并创建一个新的节点。

html中的代码如下:

 <div style="width: 50%;height: 50%">
      <el-button type="primary" @click="switchVideo(1)">切换视频1</el-button>
      <el-button type="primary" @click="switchVideo(2)">切换视频2</el-button>
      <el-button type="primary" @click="switchVideo(3)">切换m3u8视频</el-button>
      <video v-if="src" :key="src" ref="video" style="width: 100%;height: 100%; margin-top:10px" controls>
        <source :src="src" :type="type">
      </video>
 </div>

 data中的属性如下:

  data() {
    return {
      src: 'https://media.w3.org/2010/05/sintel/trailer.mp4',
      type: 'video/mp4'
    }
  },

切换方法以及播放m3u8的方法如下:

methods: {
    switchVideo(value) {
      if (value === 1) {
        this.src = 'https://video.pearvideo.com/mp4/third/20200212/cont-1651180-11487675-112807-hd.mp4';
        this.type === 'video/mp4';
      } else if (value === 2) {
        this.src = 'https://media.w3.org/2010/05/sintel/trailer.mp4';
        this.type === 'video/mp4';
      } else if (value === 3) {
        this.src = ''; //此处填写m3u8的url
        this.type === 'application/x-mpegURL';
        setTimeout(() => {
          this.m3u8Play();
        }, 500);
      } else {
        this.src = '';
        this.type === 'video/mp4';
      }
      console.log('value', value, this.src);
    },
    m3u8Play(){
      // eslint-disable-next-line no-undef
      const hls = new Hls();
      const video = this.$refs.video;
      hls.loadSource(this.src);
      hls.attachMedia(video);
      console.log('m3u8', video);
      // eslint-disable-next-line no-undef
      hls.on(Hls.Events.MANIFEST_PARSED, function() {
        video.play();
      });
    }
}

在Vue项目中引入hls.min.js可以通过npm进行安装,然后在需要使用的组件中引入并使用

npm install hls.js --save

安装好了之后,在需要用的vue组件中引入

import Hls from 'hls.js';

效果图如下,点击按钮,可以实现视频的切换

 

posted on 2024-05-07 13:46  技术高超  阅读(34)  评论(0编辑  收藏  举报