Day20 要來控制麥克風
const SpeechRecognition =
(window as any).SpeechRecognition || (window as any).webkitSpeechRecognition;
const recognition = new SpeechRecognition();
recognition.interimResults = true;
recognition.lang = "zh-TW";
const [isListening, setIsListening] = useState(false);
const [transcript, setTranscript] = useState("");
const handleResult = (event: SpeechRecognitionEvent) => {
const current = event.resultIndex;
const transcript = event.results[current][0].transcript;
setTranscript((prev) => prev + transcript + " ");
};
const handleEnd = () => {
if (isListening) {
recognition.start();
}
};
const startListening = useCallback(() => {
setIsListening(true);
setTranscript("");
recognition.onresult = handleResult as EventListener;
recognition.onend = handleEnd;
recognition.start();
}, []);
const stopListening = useCallback(() => {
setIsListening(false);
recognition.stop();
}, []);
return (
<div className="flex flex-col items-center justify-center min-h-screen bg-gray-100 p-4">
<h1 className="text-3xl font-bold mb-4">Speech Detection</h1>
<div className="w-full max-w-2xl bg-white rounded-lg shadow-md p-6">
<div className="mb-4">
<button
type="button"
onClick={isListening ? stopListening : startListening}
className={`px-4 py-2 rounded-full font-semibold text-white ${
isListening
? "bg-red-500 hover:bg-red-600"
: "bg-blue-500 hover:bg-blue-600"
}`}
>
{isListening ? "STOP" : "START"}
</button>
</div>
<div className="bg-gray-100 p-4 rounded-lg min-h-[200px] whitespace-pre-wrap">
{transcript || "Waiting for speech..."}
</div>
</div>
</div>
);
https://codesandbox.io/p/devbox/day20-speech-detection-zl7p7x