Pārlūkot izejas kodu

定时挂断语音

CzRger 3 mēneši atpakaļ
vecāks
revīzija
a21d185689
1 mainītis faili ar 15 papildinājumiem un 19 dzēšanām
  1. 15 19
      src/utils/useSpeechToAudio.ts

+ 15 - 19
src/utils/useSpeechToAudio.ts

@@ -2,8 +2,8 @@ import { onUnmounted, reactive, ref } from 'vue'
 import { ElMessage } from 'element-plus'
 
 export default function useSpeechToAudio({
-  onEnd = () => {},
-  onSpeak = () => {},
+  onEnd = (audio) => {},
+  onSpeak = ({ duration }) => {},
   timeout = 0,
 }) {
   const state: any = reactive({
@@ -13,7 +13,7 @@ export default function useSpeechToAudio({
     timer: null,
     dataArray: null,
     animationId: null,
-    timeoutTimer: null,
+    timestamp: 0,
   })
   const volume = ref(0)
   const speak = async () => {
@@ -38,8 +38,7 @@ export default function useSpeechToAudio({
         cancelAnimationFrame(state.animationId)
         clearInterval(state.timer)
         state.timer = null
-        clearInterval(state.timeoutTimer)
-        state.timeoutTimer = null
+        state.timestamp = 0
         const audioBlob = new Blob(audioChunks, { type: 'audio/mp3' })
         // this.audioUrl = URL.createObjectURL(this.audioBlob)
         stream.getTracks().forEach((track) => track.stop())
@@ -71,10 +70,6 @@ export default function useSpeechToAudio({
         state.duration = Math.floor((Date.now() - startTime) / 1000)
         onSpeak({ duration: state.duration })
       }, 1000)
-      state.timeoutTimer = setInterval(() => {
-        console.log(1)
-        stop()
-      }, 1000 * timeout)
     } catch (err: any) {
       ElMessage.error('无法访问麦克风: ' + err.message)
       console.error('录音错误:', err)
@@ -98,16 +93,17 @@ export default function useSpeechToAudio({
 
     // 将音量映射到0-100范围
     volume.value = Math.min(100, Math.max(0, Math.round(average / 2.55)))
-    console.error(volume.value)
-    if (volume.value > 10) {
-      clearInterval(state.timeoutTimer)
-      state.timeoutTimer = null
-    } else {
-      if (!state.timeoutTimer) {
-        state.timeoutTimer = setInterval(() => {
-          console.log(2)
-          stop()
-        }, 1000 * timeout)
+    if (timeout > 0) {
+      if (volume.value > 10) {
+        state.timestamp = 0
+      } else {
+        if (state.timestamp > 0) {
+          if (new Date().getTime() - state.timestamp > timeout * 1000) {
+            stop()
+          }
+        } else {
+          state.timestamp = new Date().getTime()
+        }
       }
     }
     // 继续动画