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>
相关推荐
P P PHP3 小时前
Html播放m3u8视频
音视频
小影译片3 小时前
zmaify 职场成长平台宣传视频脚本(视频计划谁能做的更好?)
音视频
weixin-a153003083164 小时前
vue疑难解答
前端·javascript·vue.js
superxxd7 小时前
跨平台音频IO处理库libsoundio实践
开发语言·qt·音视频
EasyCVR14 小时前
视频融合平台EasyCVR助力构建智慧园区的“视觉中枢”与“智能引擎”
音视频
nueroamazing14 小时前
PPT-EA:PPT自动生成器
vue.js·python·语言模型·flask·大模型·项目·ppt
皇族崛起15 小时前
【音频标注】- 音频标注开源工具 Label Studio 安装教程
音视频·label studio·音频标注·样本标注
LuckySusu17 小时前
【vue篇】Vue 项目中的静态资源管理:assets vs static 终极指南
前端·vue.js
hello_hereitis17 小时前
迅捷视频转换器 v18.4.23 图文安装教程|支持MP4、AVI、MKV等多格式视频转换
音视频·视频
LuckySusu17 小时前
【vue篇】Vue.delete vs delete:数组删除的“陷阱”与正确姿势
前端·vue.js