vue3使用西瓜播放器播放flv、hls、mp4视频

vue3使用西瓜播放器播放flv、hls、mp4视频

安装相关的插件

npm install xgplayer

npminstall xgplayer-flv

npm install xgplayer-hls

npm install xgplayer-mp4

组件封装

javascript 复制代码
<template>
  <div :id="`${playerId}`" />
</template>
<script setup lang="ts">
import Player from 'xgplayer'
import FlvPlugin from 'xgplayer-flv'
import HlsPlugin from 'xgplayer-hls'
import Mp4Plugin from 'xgplayer-mp4'
import 'xgplayer/dist/index.min.css'
import { ref, watch, onMounted, onUnmounted } from 'vue'

interface propsType {
  playerId?: string
  width?: number
  height?: number
  url: string
  plugin?: 'flv' | 'hls' | 'mp4'
  fitVideoSize?: 'fixed' | 'fixWidth' | 'fixHeight' | undefined
  controls?: boolean
}

const props = withDefaults(defineProps<propsType>(), {
  playerId: 'playerContainer',
  width: 640,
  height: 320,
  url: '',
  plugin: 'hls',
  fitVideoSize: 'fixWidth',
  controls: true
})
const player = ref<any>(null)
const clientWidth = ref<number>(1920)
const clientHeight = ref<number>(1080)

onMounted(() => {
  init()
  clientWidth.value = document.body.clientWidth
  clientHeight.value = document.body.clientHeight
  window.addEventListener(
    'resize',
    () => {
      clientWidth.value = document.body.clientWidth
      clientHeight.value = document.body.clientHeight
      init()
    },
    false
  )
})
watch(
  () => props.url,
  () => {
    init()
  },
  { deep: true }
)
const getPlugins = () => {
  let plugins = [Mp4Plugin]
  switch (props.plugin) {
    case 'hls':
      // @ts-expect-error version报错
      plugins = [HlsPlugin]
      break
    case 'flv':
      // @ts-expect-error version报错
      plugins = [FlvPlugin]
      break
    default:
      plugins = [Mp4Plugin]
      break
  }
  return plugins
}
const init = async () => {
  player.value = new Player({
    id: props.playerId,
    isLive: true,
    autoplayMuted: true,
    autoplay: true,
    plugins: await getPlugins(),
    url: props.url,
    fitVideoSize: props.fitVideoSize,
    height: props.height * (clientHeight.value / 1080),
    width: props.width * (clientWidth.value / 1920),
    lang: 'zh-cn',
    controls: props.controls
  })
}
/**
 * 销毁播放器
 */
onUnmounted(() => {
  player.value.destroy()
})
</script>
相关推荐
Можно8 小时前
深入理解 ES6 Proxy:与 Object.defineProperty 的全面对比
前端·javascript·vue.js
AF_INET610 小时前
RV1126B开发板学习篇(二)v4l2+mpp编码
c语言·经验分享·音视频·视频编解码·嵌入式软件·rv1126b
天天向上102410 小时前
vue el-table实现拖拽排序
前端·javascript·vue.js
reembarkation12 小时前
vue3中使用howler播放音频列表
前端·vue.js·音视频
要换昵称了13 小时前
Axios二次封装及API 调用框架
前端·vue.js
angerdream13 小时前
最新版vue3+TypeScript开发入门到实战教程之Pinia详解
前端·javascript·vue.js
假装没有名字13 小时前
Vue2、Vue3中的$scopedSlots和$slots区别
vue.js
BryanGG16 小时前
【说明书】索尼A7C视频拍摄PP值配置
音视频·规格说明书
带娃的IT创业者17 小时前
音乐播放器开发:QtMultimedia 音频引擎与播放列表管理
音视频·pyside6·qtmultimedia·音乐播放·qmediaplayer·播放列表·audio ducking
徐小夕17 小时前
花了一周时间,我们开源了一款PDF编辑SDK,支持在线批注+脱敏
前端·vue.js·github