@lobehub/tts
Version:
A high-quality & reliable TTS React Hooks library
72 lines (70 loc) • 2.03 kB
JavaScript
import { useOpenAISTTCore } from "./useOpenAISTTCore.mjs";
import { useSpeechRecognitionAutoStop } from "../useSpeechRecognition/useSpeechRecognitionAutoStop.mjs";
import { useCallback, useState } from "react";
//#region src/react/useOpenAISTT/useOpenAISTTAutoStop.ts
const useOpenAISTTAutoStop = (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 } = useSpeechRecognitionAutoStop(locale, {
onBlobAvailable: (blobData) => {
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 useOpenAISTTAutoStop:", err);
handleStop();
},
onSuccess: async (data, ...rest) => {
onSuccess?.(data, ...rest);
const text = (await data.json()).text;
setText(text);
onTextChange?.(text);
handleStop();
onFinished?.(data, ...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 { useOpenAISTTAutoStop };