UNPKG

beautiful-react-hooks

Version:

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

29 lines (28 loc) 1.11 kB
import { useCallback, useEffect, useMemo } from 'react'; const defaultOptions = { rate: 1, pitch: 1, volume: 1 }; /** * Enables the possibility to perform a text-to-speech (with different voices) operation in your * React component by using the Web_Speech_API */ const useSpeechSynthesis = (text, options = defaultOptions) => { const utter = useMemo(() => new SpeechSynthesisUtterance(text), [text]); const voiceOptions = Object.assign(Object.assign({}, defaultOptions), options); utter.voice = voiceOptions.voice; useEffect(() => { utter.pitch = voiceOptions.pitch; }, [voiceOptions.pitch]); useEffect(() => { utter.rate = voiceOptions.rate; }, [voiceOptions.rate]); useEffect(() => { utter.volume = voiceOptions.volume; }, [voiceOptions.volume]); const speak = useCallback(() => { speechSynthesis.speak(utter); }, [text, voiceOptions.pitch, voiceOptions.rate, voiceOptions.voice, voiceOptions.volume]); return Object.freeze({ speak, speechSynthUtterance: utter }); }; export default useSpeechSynthesis;