<template>
  <video
    class="flv-media"
    ref="VideoMedia"
    @ended="destroyPlayer"
    muted
  ></video>
</template>

<script>
import flvjs from "flv.js";

export default {
  name: "flv-media",
  props: {
    liveUrl: {
      type: String,
    },
  },
  data() {
    return {
      flvPlayer: null,
    };
  },
  mounted() {
    this.initVideo();
  },
  methods: {
    initVideo() {
      if (!this.liveUrl) return;
      if (!flvjs.isSupported()) return;

      this.flvPlayer = flvjs.createPlayer(
        {
          type: "flv",
          isLive: true,
          hasAudio: false,
          url: this.liveUrl,
        },
        {
          fixAudioTimestampGap: false,
        }
      );
      this.flvPlayer.attachMediaElement(this.$refs.VideoMedia);
      this.flvPlayer.load();
      this.flvPlayer.play();
    },
    playPlayer() {
      this.flvPlayer.play();
    },
    pausePlayer() {
      this.flvPlayer.pause();
    },
    destroyPlayer() {
      if (!this.flvPlayer) return;
      this.flvPlayer.pause();
      this.flvPlayer.unload();
      this.flvPlayer.detachMediaElement();
      this.flvPlayer.destroy();
      this.flvPlayer = null;
    },
    reloadVideo() {
      this.destroyPlayer();
      this.initVideo();
    },
  },
  beforeDestroy() {
    this.destroyPlayer();
  },
};
</script>
