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>
相关推荐
用户21366100357211 分钟前
Vue2事件系统与指令进阶
前端·vue.js
逸铭4 小时前
Day 5:三栏布局——左账号 / 中聊天 / 右工具
vue.js·electron
用户1733598075375 小时前
Vue 3 SPA 首屏优化:从 3s 到 1.2s 的 5 个实践
前端·vue.js
锋行天下1 天前
我试图优化 Vite 的拆包,结果首屏慢了 10 倍
前端·vue.js·架构
ZhengEnCi1 天前
Q02-Vue-React-index.html完全指南
vue.js·react.js·html
晴虹1 天前
vue3-scroll-more:横向滚动条-元素或页签过多滚动显示处理的组件
前端·vue.js
Forever7_1 天前
尤雨溪转发:Vue-tui 0.1 发布!Vue 终于杀进终端!
vue.js
dkbnull1 天前
Vue 虚拟 DOM Diff 算法与 key 机制原理
vue.js
前端切图崽_小郭2 天前
虚拟滚动:静态 vs 动态的核心差异与实现?
vue.js
白鲸开源2 天前
Apache SeaTunnel Zeta Engine 的 Basic Auth 是怎么工作的?
java·vue.js·github