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>
相关推荐
闲蛋小超人笑嘻嘻1 天前
Vue 的异步更新机制和 $nextTick 的用法
前端·javascript·vue.js
GhostPaints1 天前
Vue 2 项目中 template 使用可选链 ?. 导致的诡异编译报错及 webpack loader 配置坑
前端·vue.js·webpack
liuhaikang1 天前
鸿蒙VR视频播放库——md360player
音视频·vr·harmonyos
Code知行合壹1 天前
Vue.js基础入门
javascript·vue.js·ecmascript
daols881 天前
vue 表格 vxe-table 手动操作单元格范围选择,手动选择 excel 指定区域的用法
vue.js·excel·vxe-table
TEL189246224771 天前
IT6565:单芯片双通道DisplayPort 1.4转HDMI 2.0转换器,带嵌入式MCU
音视频·实时音视频·视频编解码
小二·1 天前
Vue Router 4 完全指南:动态路由、权限控制、懒加载与性能优化
前端·javascript·vue.js
豌豆学姐1 天前
AI 视频提示词怎么写:基于现有视频的 Prompt 反向解析实践
人工智能·prompt·音视频
不想秃头的程序员1 天前
Vue3 defineModel 完全指南:从基础使用到进阶技巧
前端·vue.js·面试
不想秃头的程序员1 天前
🔥Vue3 动态组件‘component’全解析
前端·vue.js·面试