<script setup>
import Recorder from 'recorder-core';
import 'recorder-core/src/engine/mp3';
import 'recorder-core/src/engine/mp3-engine'
//可选的插件支持项，把需要的插件按需引入进来即可
//import 'recorder-core/src/extensions/waveview'
import 'recorder-core/src/extensions/frequency.histogram.view'
import 'recorder-core/src/extensions/lib.fft'

import { ref } from 'vue';

let rec = null;
let processTime = 0;
let wave = null;

const recOpen = (success) => {
  rec = Recorder({
    type: "mp3",
    sampleRate: 16000,
    bitRate: 16,
    onProcess: (buffers, powerLevel, bufferDuration, bufferSampleRate) => {
      processTime = Date.now();
      wave && wave.input(buffers[buffers.length - 1], powerLevel, bufferSampleRate);
    }
  });

  rec.open(() => {
    if (Recorder.FrequencyHistogramView) wave = Recorder.FrequencyHistogramView({ 
        elem: ".recwave"
        ,lineCount:20
		,position:0
		,minHeight:1
		,fallDuration:400
		,stripeEnable:false
		,mirrorEnable:true
		,linear:[0,"#0ac",1,"#0ac"] 
    });
    success && success();
  }, (msg, isUserNotAllow) => {
    console.log((isUserNotAllow ? "UserNotAllow, " : "") + "Unable to record: " + msg);
  });

    // Create the WaveView element and prepend it to the body
    const div = document.createElement("div");
    div.innerHTML = '<div style="height:100px;width:100%;" class="recwave"></div>';
    document.body.prepend(div);
};

const startRecording = () => {
  rec.start();

  rec.watchDogTimer = setInterval(() => {
    if (!rec || rec.watchDogTimer != rec.watchDogTimer) {
      clearInterval(rec.watchDogTimer);
      return;
    }
    if (Date.now() < rec.wdtPauseT) return;
    if (Date.now() - (processTime || startTime) > 1500) {
      clearInterval(rec.watchDogTimer);
      console.error(processTime ? "Recording interrupted" : "Recording did not start properly");
      // Your error handling logic here
    }
  }, 1000);

  const startTime = Date.now();
  rec.wdtPauseT = 0;
  processTime = 0;
};

const stopRecording = () => {
  clearInterval(rec.watchDogTimer);
  rec.stop((blob, duration) => {
    const localUrl = (window.URL || webkitURL).createObjectURL(blob);
    console.log(blob, localUrl, "Duration: " + duration + "ms");

    rec.close();
    rec = null;

    var audio = document.createElement("audio");
    document.body.prepend(audio);
    audio.controls = true;
    audio.src = localUrl;
    audio.play();
  }, (msg) => {
    console.log("Recording failed: " + msg);
    rec.close();
    rec = null;
  });
};

recOpen(() => {
  // Callback after successfully opening recorder
});
</script>

<template>
    <div>
        <van-button type="primary" @click="startRecording">开始录音</van-button>
        <van-button type="primary" @click="stopRecording">停止录音</van-button>
    </div>
</template>

<style>

</style>