MCPcopy Create free account
hub / github.com/adobe/react-spectrum / useVoiceInput

Function useVoiceInput

packages/@react-spectrum/ai/src/useVoiceInput.ts:232–314  ·  view source on GitHub ↗
(options: VoiceInputProps)

Source from the content-addressed store, hash-verified

230};
231
232export const useVoiceInput = (options: VoiceInputProps): VoiceInputResult => {
233 const {lang, onError, onListeningChange} = options;
234
235 // Resolve support once — it cannot change for the lifetime of the page.
236 const ctor = useMemo(() => (isSecureVoiceContext() ? getRecognitionCtor() : null), []);
237 const isSupported = ctor !== null;
238
239 const [isListening, setIsListening] = useState(false);
240 const [errorCode, setErrorCode] = useState<VoiceInputErrorCode | null>(null);
241 const [interimTranscript, setInterimTranscript] = useState('');
242 const [finalTranscript, setFinalTranscript] = useState('');
243 const transcript = finalTranscript + interimTranscript;
244
245 const recognitionRef = useRef<SpeechRecognition | null>(null);
246 const startingRef = useRef(false);
247 const handleError = useEffectEvent((code: VoiceInputErrorCode) => {
248 onError?.(code);
249 });
250 const handleListeningChange = useEffectEvent((v: boolean) => {
251 onListeningChange?.(v);
252 });
253
254 const stop = useCallback(() => {
255 recognitionRef.current?.stop();
256 }, []);
257
258 const start = useCallback(() => {
259 // Guard against double-start (a started recognizer throws InvalidStateError)
260 // and against re-entry while the permission prompt is open.
261 if (!ctor || recognitionRef.current || startingRef.current) {
262 return;
263 }
264 startingRef.current = true;
265 setErrorCode(null);
266 setInterimTranscript('');
267 setFinalTranscript('');
268
269 // Request mic access first so the browser permission prompt reliably opens
270 // and a denial is reported before recognition starts.
271 void requestMicrophone().then(micError => {
272 startingRef.current = false;
273 if (micError) {
274 setErrorCode(micError);
275 handleError(micError);
276 return;
277 }
278 // Bail if already started while the permission prompt was open.
279 if (recognitionRef.current) {
280 return;
281 }
282
283 const recognition = createRecognizer(ctor, lang ?? navigator.language ?? 'en-US', {
284 recognitionRef,
285 setListening: setIsListening,
286 onListeningChange: handleListeningChange,
287 onError: handleError,
288 setError: setErrorCode,
289 setInterim: setInterimTranscript,

Callers 1

PromptFieldVoiceButtonFunction · 0.90

Calls 11

useEffectEventFunction · 0.90
isSecureVoiceContextFunction · 0.85
getRecognitionCtorFunction · 0.85
onErrorFunction · 0.85
requestMicrophoneFunction · 0.85
createRecognizerFunction · 0.85
abortMethod · 0.80
stopFunction · 0.70
stopMethod · 0.65
startMethod · 0.65
startFunction · 0.50

Tested by

no test coverage detected