vue3使用西瓜播放器播放flv、hls、mp4视频
安装相关的插件
npm install xgplayer
npminstall xgplayer-flv
npm install xgplayer-hls
npm install xgplayer-mp4
组件封装
<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>
如果是在微信小程序上通过web-view访问页面播放视频流时请加上'x5-video-player-type': 'h5'
'x5-video-player-type': 'h5', // 微信内置浏览器设置,防止被浏览器劫持