
<template>
    <div class="container">
        <div class="recording">
             <el-tooltip
                class="box-item"
                effect="dark"
                content="点击开始录音"
                placement="top-start"
                v-if="!isRecording"
            >
                <el-icon class="start" :size="40" @click="startRecording" ><Microphone /></el-icon>
            </el-tooltip>
            <el-tooltip
                class="box-item"
                effect="dark"
                content="点击结束录音"
                placement="top-start"
                v-if="isRecording"
            >
            <el-icon class="stop" :size="40"  @click="stopRecording"><VideoPause /></el-icon>
            </el-tooltip>
        </div>
        <div class="audio" v-if="audioUrl">
            <!-- <audio :src="audioUrl" controls /> -->
            <AudioPlayer :url="audioUrl" :recordingTime="recordingTime"/>
        </div>
    </div>  
</template>

<script setup>
import { ref } from 'vue'
import { Microphone, VideoPause } from "@element-plus/icons-vue";
import AudioPlayer from './AudioPlayer.vue';

const isRecording = ref(false)
const audioChunks = ref([])
const audioUrl = ref(null)
let mediaRecorder = null
let globalBlob = null
const recordingTime = ref(0)
let startTime

// 启动录音
const startRecording = async () => {
    audioUrl.value = null
    globalBlob = null
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
    mediaRecorder = new MediaRecorder(stream)
    mediaRecorder.onstart = () => {
      startTime = Date.now(); // 记录开始时间
    }
    mediaRecorder.ondataavailable = e => audioChunks.value.push(e.data)
    mediaRecorder.start()
    isRecording.value = true
  } catch (err) {
    console.error('麦克风权限获取失败:', err)
  }
}

// 停止录音
const stopRecording = () => {
  mediaRecorder.stop()
  mediaRecorder.onstop = () => {
    recordingTime.value = Math.round((Date.now() - startTime) / 1000);
    const blob = new Blob(audioChunks.value, { type: 'audio/m4a' })
    globalBlob = blob
    audioUrl.value = URL.createObjectURL(blob)
    audioChunks.value = []
    isRecording.value = false
  }
}

// 转换逻辑参考
const getWav = () => {
    if (globalBlob) {
        return globalBlob
    }
    return null
}

const reset = () => {
    globalBlob = null
    audioUrl.value = ''
    audioChunks.value = []
    isRecording.value = false
}

defineExpose({
    getWav,
    reset
})

</script>
<style lang="scss" scoped>
.container {
    display: flex;
    justify-content: space-evenly !important;
    align-items: center;

    .recording {
        .start {
            cursor: pointer;
        }

        .stop {
            color: #f80303;
            cursor: pointer;
        }
    }
}

</style>

