UNPKG

beautiful-react-hooks

Version:

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

51 lines (50 loc) 1.98 kB
"use strict"; var _a; Object.defineProperty(exports, "__esModule", { value: true }); var react_1 = require("react"); var 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. */ var useSpeechRecognition = function () { var spInstance = (0, react_1.useMemo)(function () { return SpeechRecognition ? new SpeechRecognition() : null; }, []); var _a = (0, react_1.useState)(false), isRecording = _a[0], setIsRecording = _a[1]; var _b = (0, react_1.useState)(''), transcript = _b[0], setTranscript = _b[1]; var isSupported = !!spInstance; (0, react_1.useEffect)(function () { var getResults = function (event) { var nextTranscript = event.results[0][0].transcript; setTranscript(nextTranscript); }; if (spInstance && isSupported) { spInstance.addEventListener('result', getResults); } return function () { if (spInstance && isSupported) { spInstance.stop(); spInstance.abort(); spInstance.removeEventListener('result', getResults); } }; }, [spInstance]); var startRecording = (0, react_1.useCallback)(function () { if (spInstance && isSupported) { spInstance.start(); setIsRecording(true); } }, [spInstance]); var stopRecording = (0, react_1.useCallback)(function () { if (spInstance && isSupported) { spInstance.stop(); setIsRecording(false); } }, [spInstance]); return Object.freeze({ isSupported: isSupported, transcript: transcript, isRecording: isRecording, startRecording: startRecording, stopRecording: stopRecording }); }; exports.default = useSpeechRecognition;