2023-06-15 12:52:46 +03:00
|
|
|
/* eslint-disable */
|
2023-06-03 21:09:00 +03:00
|
|
|
import { useEffect, useState } from "react";
|
2023-06-15 12:52:46 +03:00
|
|
|
|
|
|
|
import { isSpeechRecognitionSupported } from "@/lib/helpers/isSpeechRecognitionSupported";
|
|
|
|
|
2023-06-22 18:50:06 +03:00
|
|
|
type useSpeechProps = {
|
|
|
|
setMessage: (newValue: string | ((prevValue: string) => string)) => void;
|
|
|
|
};
|
2023-06-03 21:09:00 +03:00
|
|
|
|
2023-06-22 18:50:06 +03:00
|
|
|
export const useSpeech = ({ setMessage }: useSpeechProps) => {
|
2023-06-03 21:09:00 +03:00
|
|
|
const [isListening, setIsListening] = useState(false);
|
|
|
|
const [speechSupported, setSpeechSupported] = useState(false);
|
2023-06-11 00:59:16 +03:00
|
|
|
|
2023-06-03 21:09:00 +03:00
|
|
|
useEffect(() => {
|
|
|
|
if (isSpeechRecognitionSupported()) {
|
|
|
|
setSpeechSupported(true);
|
|
|
|
const SpeechRecognition =
|
|
|
|
window.SpeechRecognition || window.webkitSpeechRecognition;
|
|
|
|
|
|
|
|
const mic = new SpeechRecognition();
|
|
|
|
|
|
|
|
mic.continuous = true;
|
|
|
|
mic.interimResults = false;
|
|
|
|
mic.lang = "en-US";
|
|
|
|
|
|
|
|
mic.onstart = () => {
|
|
|
|
console.log("Mics on");
|
|
|
|
};
|
|
|
|
|
|
|
|
mic.onend = () => {
|
|
|
|
console.log("Mics off");
|
|
|
|
};
|
|
|
|
|
|
|
|
mic.onerror = (event: SpeechRecognitionErrorEvent) => {
|
|
|
|
console.log(event.error);
|
|
|
|
setIsListening(false);
|
|
|
|
};
|
|
|
|
|
|
|
|
mic.onresult = (event: SpeechRecognitionEvent) => {
|
|
|
|
const interimTranscript =
|
|
|
|
event.results[event.results.length - 1][0].transcript;
|
2023-06-22 18:50:06 +03:00
|
|
|
setMessage((prevMessage) => prevMessage + interimTranscript);
|
2023-06-03 21:09:00 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
if (isListening) {
|
|
|
|
mic.start();
|
|
|
|
}
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
if (mic) {
|
|
|
|
mic.stop();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
2023-06-11 00:59:16 +03:00
|
|
|
}, [isListening, setMessage]);
|
2023-06-03 21:09:00 +03:00
|
|
|
|
|
|
|
const startListening = () => {
|
|
|
|
setIsListening((prevIsListening) => !prevIsListening);
|
|
|
|
};
|
|
|
|
|
|
|
|
return { startListening, speechSupported, isListening };
|
|
|
|
};
|