File size: 1,492 Bytes
cb3a187
 
 
 
 
 
 
 
 
 
 
 
0207f3e
 
 
 
 
 
cb3a187
 
 
 
 
 
 
 
0207f3e
 
 
 
 
 
 
 
cb3a187
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import classNames from "classnames";
import { FaMicrophone } from "react-icons/fa";
import SpeechRecognition, {
  useSpeechRecognition,
} from "react-speech-recognition";
import { useUpdateEffect } from "react-use";

function SpeechPrompt({
  setPrompt,
}: {
  setPrompt: React.Dispatch<React.SetStateAction<string>>;
}) {
  const {
    transcript,
    listening,
    browserSupportsSpeechRecognition,
    resetTranscript,
  } = useSpeechRecognition();

  const startListening = () =>
    SpeechRecognition.startListening({ continuous: true });

  useUpdateEffect(() => {
    if (transcript) setPrompt(transcript);
  }, [transcript]);

  useUpdateEffect(() => {
    if (!listening) resetTranscript();
  }, [listening]);

  if (!browserSupportsSpeechRecognition) {
    return null;
  }

  return (
    <button
      className={classNames(
        "flex cursor-pointer flex-none items-center justify-center rounded-full text-sm font-semibold size-8 text-center bg-gray-800 hover:bg-gray-700 text-white shadow-sm dark:shadow-highlight/20 disabled:bg-gray-300 disabled:text-gray-500 disabled:cursor-not-allowed disabled:hover:bg-gray-300",
        {
          "animate-pulse !bg-orange-500": listening,
        }
      )}
      onTouchStart={startListening}
      onMouseDown={startListening}
      onTouchEnd={SpeechRecognition.stopListening}
      onMouseUp={SpeechRecognition.stopListening}
    >
      <FaMicrophone className="text-base" />
    </button>
  );
}

export default SpeechPrompt;