Vue CLI:中播放视频音频组件MediaElement

Lasted 2020-03-13 23:09:22

在 Vue CLI 项目中播放视频和音频可以使用 MediaElement.js 。

1. 添加 MediaElement.js

在项目中添加 MediaElement.js 可以使用 npm 或者 yarn,如下所示:

npm install mediaelement
OR
yarn add mediaelement

2. 封装 Vue 组件 

新建组件文件 VideoPlayer.vue,如下所示:

<template>
  <video
    :width="width"
    :height="height"
    :preload="preload"
    :autoplay="autoplay"
    playsinline
    webkit-playsinline
  ></video>
</template>

<script>
import 'mediaelement'

export default {
  name: 'VideoPlayer',
  props: {
    source: {
      type: String,
      required: true,
      default: ''
    },
    width: {
      type: String,
      required: false,
      default: '640'
    },
    height: {
      type: String,
      required: false,
      default: '360'
    },
    preload: {
      type: String,
      required: false,
      default: 'none'
    },
    autoplay: {
      type: Boolean,
      required: false,
      default: false
    }
  },
  data() {
    return {}
  },
  methods: {},
  mounted() {
    global.vbus.$emit('console', 'video mount')

    const { MediaElementPlayer } = global

    const vThis = this

    // eslint-disable-next-line no-new
    new MediaElementPlayer(this.$el, {
      success: function(mediaElement, originalNode, instance) {
        instance.setSrc(vThis.source)
        if (vThis.autoplay) {
          mediaElement.addEventListener('canplay', function() {
            instance.play()
          })
        }
      }
    })
  },
  source: function(src) {
    this.player.setSrc(src)
    this.player.setPoster('')
    this.player.load()
  }
}
</script>

<style type="stylesheet/scss" lang="scss" scoped>
@import '~mediaelement/build/mediaelementplayer.min.css';
</style>