<template>
  <div :style="`color:${show ? '#00CED1':'rgba(0, 0, 0, 0.3)'}`">&#xe6c1;</div>
</template>
<script>
export default {
  props: ["audioState"],
  data() {
    return {
      chunks: [],
      mediaRecorder: null,
      show: false, // true 开启，false 停止
    };
  },
  methods: {
    // 初始化音频
    async initRecorder() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({
          audio: true,
        });
        this.mediaRecorder = new MediaRecorder(stream);

        // 事件监听
        this.mediaRecorder.ondataavailable = (e) => {
          this.chunks.push(e.data);
        };
        this.mediaRecorder.onstart = () => {
          this.chunks = [];
        };
        this.mediaRecorder.onstop = () => {
          const blob = new Blob(this.chunks, {
            type: "audio/webm;codecs=opus",
          });
          this.$emit("callBack", blob);
        };
      } catch (error) {
        this.show = false;
        this.mediaRecorder = null;
        let txt = "不支持的音频";
        if (error.toString().includes("getUserMedia")) {
          txt = "不支持webrtc音频";
        } else {
          txt = "未获取到音频设备";
        }
        alert(txt)
      }
    },

    // blob2AudioBuffer
    blob2audioBuffer(blob) {
      const reader = new FileReader();
      reader.onload = function () {
        console.log(123, this.result);
        const audioCtx = new AudioContext();
        audioCtx.decodeAudioData(this.result, function (audioBuffer) {
          // AudioBuffer
          console.log(audioBuffer);
        });
      };
      reader.readAsArrayBuffer(blob);
    },
  },
  watch: {
    audioState(v) {
      if (!this.mediaRecorder) return;
      if (v) {
        this.mediaRecorder.start();
      } else {
        this.mediaRecorder.stop();
      }
      this.show = v;
    },
  },
  mounted() {
    this.initRecorder();
  },
};
</script>