<template>
  <div class="sound-record-wrapper">
    <img
      :src="microphoneStatus ? require('../../assets/record-ing-hasBg.png') : require('../../assets/record.png')"
      class="voice-play"
      @click="microphone"
    />
  </div>
</template>

<script>
import Recorder from 'js-audio-recorder'; // 录音插件

import { SaveFileByteBase64Text } from '@/api/app';

export default {
  name: 'SoundRecord',
  data() {
    return {
      recorder: new Recorder({
        sampleBits: 16, // 采样位数，支持 8 或 16，默认是16
        sampleRate: 16000, // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000
        numChannels: 1, // 声道，支持 1 或 2， 默认是1
      }),
      microphoneStatus: false, // 是否录音
    };
  },
  methods: {
    // 开始录音
    microphone() {
      if (navigator && navigator.mediaDevices) {
        const constraints = { audio: true }; // 设置只获取音频流
        navigator.mediaDevices
          .getUserMedia(constraints)
          .then(() => {
            if (this.microphoneStatus) {
              this.recorder.stop();
              // 录音结束，获取取录音数据
              let wav = this.recorder.getWAVBlob(); // 获取 WAV 数据
              this.microphoneStatus = false;
              let reader = new window.FileReader();
              reader.readAsDataURL(wav);
              reader.onloadend = () => {
                SaveFileByteBase64Text({
                  base64_text: reader.result.replace('data:audio/wav;base64,', ''),
                  file_suffix_name: 'mp3',
                }).then(({ file_id }) => {
                  this.$emit('saveWav', file_id);
                });
              };
            } else {
              // 开始录音
              this.recorder.start();
              this.microphoneStatus = true;
            }
          })
          .catch(() => {
            this.$message.warning('请打开浏览器录音权限');
          });
      } else {
        this.$message.warning('该浏览器不支持录音');
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.sound-record-wrapper {
  display: flex;
  align-items: center;

  .voice-play {
    width: 32px;
    height: 32px;
    cursor: pointer;
  }
}
</style>
