<template>
  <div>
    <div>
      <el-button class="btnClassGM" type="primary" @click="startRecorder()">{{
      !isRecord ? "开始录音" : "结束录音"
      }}</el-button>
      <el-button class="btnClassGM" type="primary" @click="playRecorder()">{{
      !isPlayerRecord ? "录音播放" : "停止播放"
      }}</el-button>
      <el-button class="btnClassGM" type="primary" @click="getMp3Data()">上传录音</el-button>

      <!-- <div style="margin: 10px auto 0; display: flex; align-items: center" v-if="LuAudioUrl">
        <span>已上传录音：</span>
        <audio :src="LuAudioUrl" controls="controls" ref="audio">
          Your browser does not support the audio element.
        </audio>
      </div> -->
    </div>
  </div>
</template>

<script>
import Recorder from "js-audio-recorder";
const lamejs = require("lamejs");

const recorder = new Recorder({
  sampleBits: 16, // 采样位数，支持 8 或 16，默认是16
  sampleRate: 48000, // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000
  numChannels: 1, // 声道，支持 1 或 2， 默认是1
  // compiling: false,(0.x版本中生效,1.x增加中) // 是否边录边转换，默认是false
});

// 绑定事件-打印的是当前录音数据
recorder.onprogress = function (params) {
  // console.log('--------------START---------------')
  // console.log('录音时长(秒)', params.duration);
  // console.log('录音大小(字节)', params.fileSize);
  // console.log('录音音量百分比(%)', params.vol);
  // console.log('当前录音的总数据([DataView, DataView...])', params.data);
  // console.log('--------------END---------------')
};
export default {
  props: [],
  data() {
    return {
      LuAudioUrl: "",
      isRecord: false,
      isPlayerRecord: false,
    };
  },
  methods: {
    // 开始录音
    startRecorder() {
      let _this = this;
      if (!_this.isRecord) {
        recorder.destroy(); // 销毁录音
        _this.isRecord = true;
        recorder.start().then(
          () => { },
          (error) => {
            _this.isRecord = false;
            // _this.$message.error(`${error.name} : ${error.message}`);
            _this.$message.error(`没有找到可使用的麦克风，或者您没有允许此网页使用麦克风`);
            // 出错了
            console.log(`${error.name} : ${error.message}`);
          }
        );
      } else {
        _this.isRecord = false;
        recorder.stop(); // 结束录音
      }
    },

    // 录音播放
    playRecorder() {
      if (!recorder.fileSize) {
        return;
      }
      if (!this.isPlayerRecord) {
        this.isPlayerRecord = true;
        recorder.play();
      } else {
        this.isPlayerRecord = false;
        recorder.stopPlay(); // 停止录音播放
      }
      recorder.onplayend = () => {
        this.isPlayerRecord = false;
        console.log("onplayend");
      };
    },

    /**
     * 文件格式转换 wav-map3
     * */
    getMp3Data() {
      if (!recorder.fileSize) {
        this.$message.error("请录音后在上传语音");
        return;
      }
      const mp3Blob = this.convertToMp3(recorder.getWAV());
      let audioFile = this.dataURLtoAudio(mp3Blob, "音频");
      console.log(audioFile);
      this.beforeUpload1(audioFile, 3);
      // recorder.download(mp3Blob, "recorder", "mp3");
    },
    convertToMp3(wavDataView) {
      // 获取wav头信息
      const wav = lamejs.WavHeader.readHeader(wavDataView); // 此处其实可以不用去读wav头信息，毕竟有对应的config配置
      const { channels, sampleRate } = wav;
      const mp3enc = new lamejs.Mp3Encoder(channels, sampleRate, 128);
      // 获取左右通道数据
      const result = recorder.getChannelData();
      const buffer = [];
      const leftData =
        result.left &&
        new Int16Array(result.left.buffer, 0, result.left.byteLength / 2);
      const rightData =
        result.right &&
        new Int16Array(result.right.buffer, 0, result.right.byteLength / 2);
      const remaining = leftData.length + (rightData ? rightData.length : 0);
      const maxSamples = 1152;
      for (let i = 0; i < remaining; i += maxSamples) {
        const left = leftData.subarray(i, i + maxSamples);
        let right = null;
        let mp3buf = null;
        if (channels === 2) {
          right = rightData.subarray(i, i + maxSamples);
          mp3buf = mp3enc.encodeBuffer(left, right);
        } else {
          mp3buf = mp3enc.encodeBuffer(left);
        }
        if (mp3buf.length > 0) {
          buffer.push(mp3buf);
        }
      }

      const enc = mp3enc.flush();
      if (enc.length > 0) {
        buffer.push(enc);
      }
      return new Blob(buffer, { type: "audio/mp3" });
    },
    dataURLtoAudio(blob, filename) {
      return new File([blob], filename, { type: "audio/mp3" });
    },
    beforeUpload1(event, type) {
      var file;
      if (type == 3) {
        file = event;
      } else {
        file = event.target.files[0];
      }
      var credentials = {
        accessKeyId: "AKIATLPEDU37QV5CHLMH",
        secretAccessKey: "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",
      }; //秘钥形式的登录上传
      window.AWS.config.update(credentials);
      window.AWS.config.region = "cn-northwest-1"; //设置区域

      var bucket = new window.AWS.S3({ params: { Bucket: "ccrb" } }); //选择桶
      var _this = this;
      const loading = this.openLoading();

      if (file) {
        var params = {
          Key:
            file.name.split(".")[0] +
            new Date().getTime() +
            "." +
            file.name.split(".")[file.name.split(".").length - 1],
          ContentType: file.type,
          Body: file,
          "Access-Control-Allow-Credentials": "*",
          ACL: "public-read",
        }; //key可以设置为桶的相抵路径，Body为文件， ACL最好要设置
        var options = {
          partSize: 2048 * 1024 * 1024,
          queueSize: 2,
          leavePartsOnError: true,
        };
        bucket
          .upload(params, options)
          .on("httpUploadProgress", function (evt) {
            //这里可以写进度条
            // console.log("Uploaded : " + parseInt((evt.loaded * 80) / evt.total) + '%');
            // _this.progress = parseInt((evt.loaded * 80) / evt.total);
          })
          .send(function (err, data) {
            // _this.progress = 100;
            setTimeout(() => {
              loading.close();
            }, 1000);
            if (err) {
              var a = _this.$refs.upload1.uploadFiles;
              a.splice(a.length - 1, a.length);
              _this.$message.error("上传失败");
            } else {
              if (type == 3) {
                _this.LuAudioUrl = data.Location;
                // _this.addWork(8);
                _this.addPz(data.Location);
              }
              console.log(data.Location);
            }
          });
      }
    },
    addPz(audio) {
      this.$emit("addPz", '2',audio);
    },
  },
  mounted() { },
};
</script>

<style scoped>
.mask {
  background-color: rgba(0, 0, 0, 0);
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 20000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.progressBox {
  width: 500px;
  height: 180px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 0 6px 1px #bfbfbf;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

.progressBox .lbox {
  height: 100px;
  font-size: 19px;
  display: flex;
  align-items: center;
}

.progressBox .lbox img {
  width: 40px;
  margin-right: 20px;
}

.progressBox>>>.el-progress-bar__outer {
  background-color: #d1dfff !important;
}

.progressBox .lbox {
  height: 100px;
  font-size: 19px;
  display: flex;
  align-items: center;
}

.progressBox .lbox img {
  width: 40px;
  margin-right: 20px;
}
</style>