vue3使用西瓜播放器播放flv、hls、mp4视频

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', // 微信内置浏览器设置,防止被浏览器劫持

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值