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>
相关推荐
昨日之日20069 小时前
LongCat-Video-Avatar-1.5 - 一句话生成口型同步、动作稳定的数字人 说话/唱歌 视频 一键整合包下载
音视频
searchforAI9 小时前
长视频和播客怎么变成结构化读书笔记?一套 AI 时代的知识管理方法
人工智能·笔记·gpt·音视频·语音识别
码上暴富10 小时前
el-table表格全屏/管理显示字段/导出功能封装
vue.js
不想吃饭e10 小时前
uniapp-图片,视频上传组件封装
java·uni-app·音视频
超人不会飞_Jay11 小时前
26.6.3Vue笔记
前端·vue.js·笔记
做萤石二次开发的哈哈11 小时前
具备 ERTC 能力的萤石设备如何对接客户端通话?
音视频·实时音视频·萤石开放平台
御坂1002711 小时前
Vue - @change应用实现下拉框联动功能
前端·javascript·vue.js
瘦瘦瘦大人11 小时前
Vue 项目实现关闭/刷新浏览器窗口前的离开确认提示
前端·javascript·vue.js
电子元件小说家11 小时前
音频调音台直滑电位器选型:ALPS RK12L123000E 与国产同于科技替代方案评估
科技·音视频
belong_my_offer11 小时前
认识前端路由& VSCode 实操
vue.js