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>
相关推荐
我有一个object1 天前
uniapp上传文件报错:targetSdkVersion设置>=29后在Android10+系统设备不支持当前路径。请更改为应用运行路径!
前端·javascript·vue.js·uniapp
aqi001 天前
FFmpeg开发笔记(九十一)基于Kotlin的Android直播开源框架RootEncoder
android·ffmpeg·kotlin·音视频·直播·流媒体
_Kayo_1 天前
vue3 computed 练习笔记
前端·vue.js·笔记
艾小码1 天前
Vue3 脚本革命:<script setup> 让你的代码简洁到飞起!
前端·javascript·vue.js
菜泡泡@1 天前
仓库地图vue-grid-layout
前端·javascript·vue.js
2013编程爱好者1 天前
Vue工程结构分析
前端·javascript·vue.js·typescript·前端框架
change_fate1 天前
el-menu折叠后文字下移
前端·javascript·vue.js
天外天-亮1 天前
Vue + excel下载 + 水印
前端·vue.js·excel
柳鲲鹏1 天前
OpenCV:文件视频防抖,python版
python·opencv·音视频
柳鲲鹏1 天前
OpenCV:实时视频防抖,python版(改进连续帧处理)
音视频