UNPKG

@lobehub/tts

Version:

A high-quality & reliable TTS React Hooks library

77 lines (75 loc) 2.13 kB
import { useOpenAISTTCore } from "./useOpenAISTTCore.mjs"; import { useSpeechRecognitionInteractive } from "../useSpeechRecognition/useSpeechRecognitionInteractive.mjs"; import { useCallback, useState } from "react"; //#region src/react/useOpenAISTT/useOpenAISTTInteractive.ts const useOpenAISTTInteractive = (locale, { onBlobAvailable, onTextChange, onSuccess, onError, onFinished, onStart, onStop, options, onRecognitionStop, onRecognitionStart, onRecognitionError, onRecognitionFinish, ...restConfig } = {}) => { const [isGlobalLoading, setIsGlobalLoading] = useState(false); const [shouldFetch, setShouldFetch] = useState(false); const [text, setText] = useState(); const { start, stop, blob, url, isRecording, time, formattedTime } = useSpeechRecognitionInteractive(locale, { onBlobAvailable: (blobData) => { if (!text || !blobData) { setIsGlobalLoading(false); stop(); return; } setShouldFetch(true); onBlobAvailable?.(blobData); }, onRecognitionError, onRecognitionFinish, onRecognitionStart, onRecognitionStop, onTextChange: (data) => { setText(data); onTextChange?.(data); } }); const handleStart = useCallback(() => { onStart?.(); setIsGlobalLoading(true); start(); setText(""); }, [start]); const handleStop = useCallback(() => { onStop?.(); stop(); setShouldFetch(false); setIsGlobalLoading(false); }, [stop]); const { isLoading, error, mutate, data: response } = useOpenAISTTCore({ onError: (err, ...rest) => { onError?.(err, ...rest); console.error("Error useOpenAISTTInteractive:", err); handleStop(); }, onSuccess: async (res, ...rest) => { onSuccess?.(res, ...rest); const text = (await res.json()).text; setText(text); onTextChange?.(text); handleStop(); onFinished?.(res, ...rest); }, options, shouldFetch, speech: blob, ...restConfig }); return { blob, error, formattedTime, isLoading: isGlobalLoading || isLoading || isRecording, isRecording, mutate, response, start: handleStart, stop: handleStop, text, time, url }; }; //#endregion export { useOpenAISTTInteractive };