<template>
  <div>
    <van-button class="mt-50" @click="openPermission">打开录音权限</van-button>
    <div class="flex">
      <van-button class="mt-50" @click="startRecording">开始录音</van-button>
      <van-button class="mt-50" @click="stopRecording">关闭并下载录音</van-button>
    </div>
  </div>
</template>
<script setup>
// https://github.com/xiangyuecn/Recorder
// import VConsole from 'vconsole';
import Recorder from "recorder-core";
//需要使用到的音频格式编码引擎
import 'recorder-core/src/engine/mp3'
import 'recorder-core/src/engine/mp3-engine'
//可选的扩展编码引擎
import 'recorder-core/src/extensions/waveview'
// new VConsole({ theme: 'dark' });

const videoConfig = {
  type: 'mp3',
  bitRate: 16,
  sampleRate: 16000,
  duration: 0,
  durationTxt: "0",
  powerLevel: 0,
  logs: []
}
let recorderInstance = null
const openPermission = () => {
  recorderInstance = Recorder({
    type: 'mp3',
    bitRate: 16,
    sampleRate: 16000,
    duration: 0,
    onProcess: function (buffers, powerLevel, duration, sampleRate) {
      console.log('录制中~')
    }
  });
  recorderInstance.open(function () {
    alert('录音已打开')
  }, function (msg, isUserNotAllow) {
    alert('录音打开失败')
  });
}

const startRecording = () => {
  try {
    if (!recorderInstance || !Recorder.IsOpen()) {
      alert('未打开录音')
      return
    }
    alert('开始录音')
    recorderInstance.start()
  } catch (e) {
    alert(e)
  }
}
const stopRecording = () => {
  if (!recorderInstance || !Recorder.IsOpen()) {
    alert('未打开录音')
    return
  }
  recorderInstance.stop(
      (blob, duration) => {
        alert('录制成功')
        const o = {
          blob: blob,
          duration: duration,
          durationTxt: formatMs(duration),
          rec: recorderInstance
        }
        let name = "rec-" + o.duration + "ms-" + (o.rec.set.bitRate || "-") + "kbps-" + (o.rec.set.sampleRate || "-") + "hz." + (o.rec.set.type || (/\w+$/.exec(o.blob.type) || [])[0] || "unknown");
        let downA = document.createElement("A");
        downA.href = (window.URL || webkitURL).createObjectURL(o.blob);
        downA.download = name;
        downA.click();
        alert('下载成功')
      },
      (e) => {
        alert(e + '录音失败')
      }
  )


}


const formatMs = (ms, all) => {
  let ss = ms % 1000;
  ms = (ms - ss) / 1000;
  let s = ms % 60;
  ms = (ms - s) / 60;
  let m = ms % 60;
  ms = (ms - m) / 60;
  let h = ms;
  let t = (h ? h + ":" : "")
      + (all || h + m ? ("0" + m).substr(-2) + ":" : "")
      + (all || h + m + s ? ("0" + s).substr(-2) + "″" : "")
      + ("00" + ss).substr(-3);
  return t;
}

</script>
<style scoped lang="scss">
* {
  user-select: none;
}
</style>