UNPKG

@lobehub/tts

Version:

A high-quality & reliable TTS React Hooks library

58 lines (56 loc) 1.76 kB
import { useAudioRecorder } from "../useAudioRecorder/index.mjs"; import { useSpeechRecognitionCore } from "./useSpeechRecognitionCore.mjs"; import { useCallback, useEffect, useState } from "react"; //#region src/react/useSpeechRecognition/useSpeechRecognitionInteractive.ts const useSpeechRecognitionInteractive = (locale, { onBlobAvailable, onTextChange, onRecognitionFinish, onStop, onStart, ...rest } = {}) => { const [resultText, setResultText] = useState(); const [texts, setTexts] = useState([]); const [isGLobalLoading, setIsGlobalLoading] = useState(false); const { time, formattedTime, start: startRecord, stop: stopRecord, blob, url } = useAudioRecorder(onBlobAvailable); const { text, stop, start, isLoading } = useSpeechRecognitionCore(locale, { onRecognitionFinish: (data) => { if (isGLobalLoading && !isLoading) { if (data) setTexts([...texts, data]); start(); } }, ...rest }); const handleStart = useCallback(() => { onStart?.(); setTexts([]); setIsGlobalLoading(true); start(); startRecord(); }, [start, startRecord]); const handleStop = useCallback(() => { onStop?.(); stop(); stopRecord(); setIsGlobalLoading(false); if (resultText) onRecognitionFinish?.(resultText); }, [ stop, stopRecord, resultText ]); useEffect(() => { const mergedText = [...texts, text].filter(Boolean).join(" "); setResultText(mergedText); onTextChange?.(mergedText); }, [texts, text]); return { blob, formattedTime, isLoading: isGLobalLoading, isRecording: isGLobalLoading, response: new Response(JSON.stringify({ text: resultText }), { status: 200 }), start: handleStart, stop: handleStop, text: resultText, time, url }; }; //#endregion export { useSpeechRecognitionInteractive };