|
| 1 | +# useSpeechRecognition |
| 2 | +Hook to use _SpeechRecognition API_. Refer to [Web Speech API](https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition). |
| 3 | + |
| 4 | +## Usage |
| 5 | + |
| 6 | +```tsx |
| 7 | +export const UseSpeechRecognition = () => { |
| 8 | + const colors = ['aqua', 'azure', 'beige', 'bisque', 'black', 'blue', 'brown', 'chocolate', 'coral', 'crimson', 'cyan', 'fuchsia', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'indigo', 'ivory', 'khaki', 'lavender', 'lime', 'linen', 'magenta', 'maroon', 'moccasin', 'navy', 'olive', 'orange', 'orchid', 'peru', 'pink', 'plum', 'purple', 'red', 'salmon', 'sienna', 'silver', 'snow', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'white', 'yellow', 'transparent'] |
| 9 | + const grammar = `#JSGF V1.0; grammar colors; public <color> = ${colors.join(' | ')} ;` |
| 10 | + |
| 11 | + const btnRef = useRef<HTMLButtonElement>(); |
| 12 | + const perform = usePerformAction(() => btnRef.current?.focus()); |
| 13 | + |
| 14 | + const [message, setMessage] = useState("Ready"); |
| 15 | + |
| 16 | + const [state, start, stop] = useSpeechRecognition({ |
| 17 | + onStart: useCallback(() => { |
| 18 | + console.log("onStart"); |
| 19 | + setMessage("Listening...") |
| 20 | + }, []), |
| 21 | + onEnd: useCallback(() => { |
| 22 | + console.log("onEnd"); |
| 23 | + setMessage("Finish"); |
| 24 | + }, []), |
| 25 | + onAudioEnd: () => { |
| 26 | + console.log("onAudioEnd"); |
| 27 | + }, |
| 28 | + onAudioStart: () => { |
| 29 | + console.log("onAudioStart"); |
| 30 | + }, |
| 31 | + onSoundStart: () => { |
| 32 | + console.log("onSoundStart"); |
| 33 | + }, |
| 34 | + onSoundEnd: () => { |
| 35 | + console.log("onSoundEnd"); |
| 36 | + }, |
| 37 | + onSpeechStart: () => { |
| 38 | + console.log("onSpeechStart"); |
| 39 | + }, |
| 40 | + onSpeechEnd: () => { |
| 41 | + console.log("onSpeechEnd"); |
| 42 | + }, |
| 43 | + onNoMatch: useCallback(() => { |
| 44 | + console.log("onNoMatch"); |
| 45 | + setMessage("Color not recognized.") |
| 46 | + }, []), |
| 47 | + onResult: useCallback(() => { |
| 48 | + console.log("onResult"); |
| 49 | + stop(); |
| 50 | + setMessage("Ready"); |
| 51 | + perform(); |
| 52 | + }, []), |
| 53 | + onError: useCallback((ev: SpeechRecognitionErrorEvent) => { |
| 54 | + console.log("onError"); |
| 55 | + setMessage(`Error occurred in recognition: ${ev.message ? ev.message : ev.error}`); |
| 56 | + }, []), |
| 57 | + }); |
| 58 | + |
| 59 | + const onStart = () => { |
| 60 | + const grammars = new SpeechGrammarListP() as SpeechGrammarList; |
| 61 | + grammars.addFromString(grammar, 1); |
| 62 | + start({ |
| 63 | + lang: "en-US", |
| 64 | + continuous: true, |
| 65 | + interimResults: false, |
| 66 | + maxAlternatives: 1, |
| 67 | + grammars |
| 68 | + }); |
| 69 | + } |
| 70 | + |
| 71 | + const color = useMemo(() => { |
| 72 | + let colr = "transparent"; |
| 73 | + if (state.result.results) { |
| 74 | + const color = state.result.results[0][0].transcript; |
| 75 | + if (colors.includes(color)) { |
| 76 | + colr = color; |
| 77 | + } |
| 78 | + } |
| 79 | + return colr; |
| 80 | + }, [state.result, colors]); |
| 81 | + |
| 82 | + return <div style={{ display: "flex", flexDirection: "column", justifyContent: "center", gap: 10 }}> |
| 83 | + { |
| 84 | + state.isSupported |
| 85 | + ? <> |
| 86 | + <div style={{ display: 'flex', flexDirection: 'column' }}> |
| 87 | + <p>Click on start to say a color to change backgroundColor of bordered div. Try</p> |
| 88 | + <div style={{ display: 'flex', flexWrap: "wrap", gap: 10 }}> |
| 89 | + { |
| 90 | + colors.map(el => <span key={el} style={{ color: el }}>{el}</span>) |
| 91 | + } |
| 92 | + </div> |
| 93 | + </div> |
| 94 | + <p>{message}</p> |
| 95 | + <div style={{ border: "1px solid lightgray", width: 300, height: 150, backgroundColor: color, margin: '0 auto' }}> |
| 96 | + { |
| 97 | + state.result && <p>Color is: {color}</p> |
| 98 | + } |
| 99 | + </div> |
| 100 | + <div style={{ display: 'flex', justifyContent: "center", gap: 10 }}> |
| 101 | + <button ref={btnRef} onClick={onStart} disabled={state.isListening}>Start</button> |
| 102 | + </div> |
| 103 | + </> |
| 104 | + : <p>Speech Recognition not supported</p> |
| 105 | + } |
| 106 | + </div> |
| 107 | +} |
| 108 | +``` |
| 109 | + |
| 110 | +> This component use _useSpeechRecognition_ hook to simulate a Speech color change app. When button _start_ is clicked, you can say an HTML color keyword and the bordered div color will change to that color. |
| 111 | +
|
| 112 | + |
| 113 | +## API |
| 114 | + |
| 115 | +```tsx |
| 116 | +useSpeechRecognition({ defaultConfig, onAudioStart, onAudioEnd, onEnd, onError, onNoMatch, onResult, onSoundStart, onSoundEnd, onSpeechStart, onSpeechEnd, onStart }: { defaultConfig?: SpeechRecognitionConfig, onAudioStart?: SpeechRecognition["onaudiostart"], onAudioEnd?: SpeechRecognition["onaudioend"], onEnd?: SpeechRecognition["onend"], onError?: SpeechRecognition["onerror"], onNoMatch?: SpeechRecognition["onnomatch"], onResult?: SpeechRecognition["onresult"], onSoundStart?: SpeechRecognition["onsoundstart"], onSoundEnd?: SpeechRecognition["onsoundend"], onSpeechStart?: SpeechRecognition["onspeechstart"], onSpeechEnd?: SpeechRecognition["onspeechend"], onStart?: SpeechRecognition["onstart"] }): [{isSupported: boolean, isListening: boolean, result: {results: SpeechRecognitionEvent["results"]|null, resultIndex: SpeechRecognitionEvent["resultIndex"]|null}}, (config?: SpeechRecognitionConfig)=>void, ()=>void] |
| 117 | +``` |
| 118 | + |
| 119 | +> ### Params |
| 120 | +> |
| 121 | +> - __opts__: _Object_ |
| 122 | +options. |
| 123 | +> - __opts.defaultConfig?__: _Object_ |
| 124 | +config parameters for current SpeechRecognition. |
| 125 | +> - __opts.defaultConfig.grammars?__: _SpeechGrammarList_ |
| 126 | +a _SpeechGrammarList_ containing the SpeechGrammar objects that represent your grammar for your app. |
| 127 | +> - __opts.defaultConfig.lang?__: _LanguageBCP47Tags_ |
| 128 | +a string representing the BCP 47 language tag for the current SpeechRecognition. |
| 129 | +> - __opts.defaultConfig.continuous?__: _boolean_ |
| 130 | +a boolean value representing the current SpeechRecognition's continuous status. true means continuous, and false means not continuous (single result each time.). |
| 131 | +> - __opts.defaultConfig.interimResults?__: _boolean_ |
| 132 | +a boolean value representing the state of the current SpeechRecognition's interim results. true means interim results are returned, and false means they aren't. |
| 133 | +> - __opts.defaultConfig.maxAlternatives?__: _number_ |
| 134 | +a number representing the maximum returned alternatives for each result. |
| 135 | +> - __opts.onAudioStart?__: _((this: SpeechRecognition, ev: Event) => void) | null_ |
| 136 | +function that will be executed when _audiostart_ event is dispatched. |
| 137 | +> - __opts.onAudioEnd?__: _((this: SpeechRecognition, ev: Event) => void) | null_ |
| 138 | +function that will be executed when _audioend_ event is dispatched. |
| 139 | +> - __opts.onEnd?__: _((this: SpeechRecognition, ev: Event) => void) | null_ |
| 140 | +function that will be executed when _end_ event is dispatched. |
| 141 | +> - __opts.onError?__: _((this: SpeechRecognition, ev: SpeechRecognitionErrorEvent) => void) | null_ |
| 142 | +function that will be executed when _error_ event is dispatched. |
| 143 | +> - __opts.onNoMatch?__: _((this: SpeechRecognition, ev: SpeechRecognitionEvent) => void) | null_ |
| 144 | +function that will be executed when _nomatch_ event is dispatched. |
| 145 | +> - __opts.onResult?__: _((this: SpeechRecognition, ev: SpeechRecognitionEvent) => void) | null_ |
| 146 | +function that will be executed when _result_ event is dispatched. |
| 147 | +> - __opts.onSoundStart?__: _((this: SpeechRecognition, ev: Event) => void) | null_ |
| 148 | +function that will be executed when _soundstart_ event is dispatched. |
| 149 | +> - __opts.onSoundEnd?__: _((this: SpeechRecognition, ev: Event) => void) | null_ |
| 150 | +function that will be executed when _soundend_ event is dispatched. |
| 151 | +> - __opts.onSpeechStart?__: _((this: SpeechRecognition, ev: Event) => void) | null_ |
| 152 | +function that will be executed when _speechstart_ event is dispatched. |
| 153 | +> - __opts.onSpeechEnd?__: _((this: SpeechRecognition, ev: Event) => void) | null_ |
| 154 | +function that will be executed when _speechend_ event is dispatched. |
| 155 | +> - __opts.onStart?__: _((this: SpeechRecognition, ev: Event) => void) | null_ |
| 156 | +function that will be executed when _start_ event is dispatched. |
| 157 | +> |
| 158 | +
|
| 159 | +> ### Returns |
| 160 | +> |
| 161 | +> __result__: __Array__: |
| 162 | + - __Object__: |
| 163 | + - __isSupported__ : _boolean_ |
| 164 | + - __isListening__ : _boolean_ |
| 165 | + - _result:{results: SpeechRecognitionEvent["results"]|null, resultIndex:SpeechRecognitionEvent["resultIndex"]|null}_ |
| 166 | + - _(config?: SpeechRecognitionConfig)=>void_ |
| 167 | + - _()=>void_ |
| 168 | +> - 1. __state__: object with these properties: |
| 169 | +> - _isSupported_: returns a boolean to know if API is available. |
| 170 | +> - _isListening_: returns a boolean indicating current SpeechRecognition execution or not. |
| 171 | +> - _result_: returns result of SpeechRecognition execution. |
| 172 | +> - 2. __start__: function to start SpeechRecognition. |
| 173 | +> - 3. __stop__: function to stop SpeechRecognition. |
| 174 | +> |
0 commit comments