VideoPlay.vue 2.84 KB
<script lang="ts" setup>
  import { isNumber } from 'lodash';
  import videoJs, { VideoJsPlayer, VideoJsPlayerOptions } from 'video.js';
  import 'video.js/dist/video-js.css';
  import { computed, CSSProperties, onMounted, onUnmounted, ref, unref } from 'vue';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { getJwtToken, getShareJwtToken } from '/@/utils/auth';
  import { isShareMode } from '/@/views/sys/share/hook';
  import 'videojs-flvjs-es6';
  const { prefixCls } = useDesign('basic-video-play');

  const props = defineProps<{
    options?: VideoJsPlayerOptions;
    withToken?: boolean;
  }>();

  const emit = defineEmits<{
    (event: 'ready', instance?: Nullable<VideoJsPlayer>): void;
    (event: 'onUnmounted'): void;
  }>();

  const videoPlayEl = ref<HTMLVideoElement>();

  const videoPlayInstance = ref<Nullable<VideoJsPlayer>>();

  const getOptions = computed(() => {
    const { options, withToken } = props;
    const defaultOptions: VideoJsPlayerOptions & Recordable = {
      language: 'zh',
      muted: true,
      liveui: true,
      controls: true,
      techOrder: ['html5', 'flvjs'],
      flvjs: {
        mediaDataSource: {
          isLive: true,
          cors: true,
          hasAudio: false,
          withCredentials: false,
          autoCleanupSourceBuffer: true,
          autoCleanupMaxBackwardDuration: 60,
        },
        config: {
          headers: {
            ...(withToken
              ? {
                  'X-Authorization': `Bearer ${isShareMode() ? getShareJwtToken() : getJwtToken()}`,
                }
              : {}),
          },
        },
      },
    };

    return { ...defaultOptions, ...options };
  });

  const getWidthHeight = computed(() => {
    let { width = 300, height = 150 } = unref(getOptions);
    width = isNumber(width) ? (`${width}px` as unknown as number) : width;
    height = isNumber(height) ? (`${height}px` as unknown as number) : height;
    return { width, height } as CSSProperties;
  });

  const init = () => {
    videoPlayInstance.value = videoJs(unref(videoPlayEl)!, unref(getOptions), () => {
      emit('ready', unref(videoPlayInstance));
    });
  };

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

  onUnmounted(() => {
    unref(videoPlayInstance)?.dispose();
    videoPlayInstance.value = null;
    emit('onUnmounted');
  });
</script>

<template>
  <div :class="prefixCls" class="w-full h-full" :style="getWidthHeight">
    <video
      ref="videoPlayEl"
      class="video-js vjs-big-play-centered vjs-show-big-play-button-on-pause !w-full !h-full"
      muted
    >
    </video>
  </div>
</template>

<style lang="less">
  @prefix-cls: ~'@{namespace}-basic-video-play';

  .@{prefix-cls} {
    .vjs-error-display {
      .vjs-modal-dialog-content::after {
        content: '无法加载视频,原因可能是服务器或网络故障,也可能是格式不支持.';
      }
    }
  }
</style>