(options: UseSpeechOptions)
| 22 | } |
| 23 | |
| 24 | function useSpeech(options: UseSpeechOptions): SpeechControls { |
| 25 | const { |
| 26 | text, |
| 27 | language = "en-US", |
| 28 | voiceURI, |
| 29 | onEnd = noop, |
| 30 | volume = 1, |
| 31 | pitch = 1, |
| 32 | rate = 1, |
| 33 | } = options; |
| 34 | |
| 35 | const freshOnEnd = useFreshCallback(onEnd); |
| 36 | |
| 37 | const speechRef = useRef<SpeechSynthesisUtterance | null>(null); |
| 38 | const [isPlaying, setIsPlaying] = useState(false); |
| 39 | |
| 40 | useEffect(() => { |
| 41 | if (speechRef.current && isPlaying) { |
| 42 | speechRef.current.text = text; |
| 43 | speechRef.current.lang = language; |
| 44 | speechRef.current.volume = volume; |
| 45 | speechRef.current.pitch = pitch; |
| 46 | speechRef.current.rate = rate; |
| 47 | |
| 48 | if (voiceURI) { |
| 49 | const voices = window.speechSynthesis.getVoices(); |
| 50 | const selectedVoice = voices.find( |
| 51 | (voice) => voice.voiceURI === voiceURI |
| 52 | ); |
| 53 | if (selectedVoice) { |
| 54 | speechRef.current.voice = selectedVoice; |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | }, [text, isPlaying, language, voiceURI, volume, pitch, rate]); |
| 59 | |
| 60 | const start = useCallback(() => { |
| 61 | if (!("speechSynthesis" in window)) { |
| 62 | console.error("Web Speech API is not supported in your browser."); |
| 63 | return; |
| 64 | } |
| 65 | |
| 66 | if (speechRef.current) { |
| 67 | window.speechSynthesis.cancel(); |
| 68 | } |
| 69 | |
| 70 | speechRef.current = new SpeechSynthesisUtterance(text); |
| 71 | speechRef.current.lang = language; |
| 72 | speechRef.current.volume = volume; |
| 73 | speechRef.current.pitch = pitch; |
| 74 | speechRef.current.rate = rate; |
| 75 | |
| 76 | if (voiceURI) { |
| 77 | const voices = window.speechSynthesis.getVoices(); |
| 78 | const selectedVoice = voices.find((voice) => voice.voiceURI === voiceURI); |
| 79 | if (selectedVoice) { |
| 80 | speechRef.current.voice = selectedVoice; |
| 81 | } |
no test coverage detected
searching dependent graphs…