vue使用video.js实现播放m3u8格式的视频

一、安装video.js

npm install video.js


我使用的video.js版本如下:

"video.js": "^7.20.3"

二、VideoPlayer组件

在components下新建一个VideoPlayer文件夹

index如下:

<template>
  <div ref="videoDiv"></div>
</template>

<script>
export default {
  name: "VideoPlayer",
  data() {
    return {
      player: null,
    };
  },
  props: {
    sourceUrl: {
      type: String,
      default: "",
    },
  },
  mounted() {
    this.initVideo();
  },
  watch: {
    sourceUrl: {
      handler(val) {
        this.initVideo();
      },
    },
  },
  methods: {
    initVideo() {
      // video标签无法动态加载src,所以在vue中如果是动态写入视频地址,js加载在HTML渲染之后,会导致video在取src时无法解析。
      // 所以需要用js在获取到src值之后生成HTML元素
      this.$refs.videoDiv.innerHTML =
        '<video class="video-js vjs-default-skin vjs-big-play-centered">' +
        "</video>";
      this.player = this.$video(this.$refs.videoDiv.firstElementChild, {
        //确定播放器是否具有用户可以与之交互的控件。没有控件,启动视频播放的唯一方法是使用autoplay属性或通过Player API。
        controls: true,
        //自动播放属性,muted:静音播放
        autoplay: "muted",
        //建议浏览器是否应在<video>加载元素后立即开始下载视频数据。
        preload: "auto",
        //设置视频播放器的显示宽度(以像素为单位)
        width: "550px",
        //设置视频播放器的显示高度(以像素为单位)
        height: "366px",
        sources: [
          {
            src: this.sourceUrl,
            type: "application/x-mpegURL",
          },
        ],
      });
    },
  },
  beforeDestroy() {
    if (this.player != null) {
      this.player.dispose(); // dispose()会直接删除Dom元素
    }
  },
};
</script>

三、main.js里注册

//video.js
import Video from "video.js";
import "video.js/dist/video-js.css";
Vue.prototype.$video = Video;

四、使用 

 直接把地址传给sourceUrl即可

<VideoPlayer :sourceUrl="sourceUrl"></VideoPlayer>
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值