Skip to content

使用说明

基本用法

视频格式:m3u8

视频格式:MP4

视频格式:FLV

查看代码
XGPlayer.vue
vue
<script setup>
import { onMounted, onUnmounted, ref, watch } from "vue";
import Player from "xgplayer";
import FlvPlayer from "xgplayer-flv";
import HlsPlayer from "xgplayer-hls";
import Mp4Player from "xgplayer-mp4";
import "xgplayer/dist/index.min.css";

const props = defineProps({
  url: {
    type: String,
    required: true,
  },
  type: {
    type: String,
    default: "auto",
  },
  options: {
    type: Object,
    default: () => ({
      height: "300",
      width: "400",
      fluid: true,
      fitVideoSize: "auto",
      volume: 0.6,
      autoplay: false,
      loop: false,
      videoInit: true,
      poster: "",
      playbackRate: [0.5, 0.75, 1, 1.5, 2],
      defaultPlaybackRate: 1,
      playsinline: true,
      whitelist: [""],
      keyShortcut: "on",
      closeVideoClick: true,
      closeVideoDblclick: true,
      closeVideoTouch: true,
      pip: true,
      download: true,
    }),
  },
});

const player = ref(null);
const playerId = `player_${Math.random().toString(36).substring(2, 9)}`;

const initPlayer = () => {
  const options = {
    id: playerId,
    url: props.url,
    ...props.options,
    plugins: []
  };

  const type = props.type === "auto" ? props.url.split(".").at(-1) : props.type;
  switch (type) {
    case "m3u8":
      options.plugins = [HlsPlayer];
      break;
    case "flv":
      options.plugins = [FlvPlayer];
      break;
    case "mp4":
      options.plugins = [Mp4Player];
      break;
    default:
      options.plugins = [];
  }

  if (player.value) {
    player.value.destroy();
  }

  player.value = new Player(options);
};

watch(
  () => [props.url, props.type],
  () => {
    initPlayer();
  }
);

watch(
  () => props.options,
  () => {
    initPlayer();
  },
  { deep: true }
);

onMounted(() => {
  initPlayer();
});

onUnmounted(() => {
  // 销毁旧播放器
  if (player.value) {
    player.value.destroy();
  }
});

const playerRef = ref();

defineExpose({
  player: player.value, // 暴露player实例
  domRef: playerRef, // 暴露player元素
});
</script>

<template>
  <div :id="playerId" ref="playerRef"></div>
</template>

<style lang="scss" scoped></style>

上次更新:

关注公众号