UNPKG

beautiful-react-hooks

Version:

A collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development

49 lines (48 loc) 1.72 kB
var _a; import { useCallback, useEffect, useMemo, useState } from 'react'; const SpeechRecognition = (_a = window.SpeechRecognition) !== null && _a !== void 0 ? _a : window.webkitSpeechRecognition; /** * A hook that provides an interface for using the Web Speech API to recognize and transcribe speech in a user's browser. */ const useSpeechRecognition = () => { const spInstance = useMemo(() => SpeechRecognition ? new SpeechRecognition() : null, []); const [isRecording, setIsRecording] = useState(false); const [transcript, setTranscript] = useState(''); const isSupported = !!spInstance; useEffect(() => { const getResults = (event) => { const nextTranscript = event.results[0][0].transcript; setTranscript(nextTranscript); }; if (spInstance && isSupported) { spInstance.addEventListener('result', getResults); } return () => { if (spInstance && isSupported) { spInstance.stop(); spInstance.abort(); spInstance.removeEventListener('result', getResults); } }; }, [spInstance]); const startRecording = useCallback(() => { if (spInstance && isSupported) { spInstance.start(); setIsRecording(true); } }, [spInstance]); const stopRecording = useCallback(() => { if (spInstance && isSupported) { spInstance.stop(); setIsRecording(false); } }, [spInstance]); return Object.freeze({ isSupported, transcript, isRecording, startRecording, stopRecording }); }; export default useSpeechRecognition;