From f9ed2ad8db6ec8189a755d0f22133c9051a3adb2 Mon Sep 17 00:00:00 2001 From: bsu3338 Date: Wed, 9 Aug 2023 00:57:57 -0500 Subject: [PATCH] Create SpeechSynthesis.tsx --- .../components/Messages/SpeechSynthesis.tsx | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 client/src/components/Messages/SpeechSynthesis.tsx diff --git a/client/src/components/Messages/SpeechSynthesis.tsx b/client/src/components/Messages/SpeechSynthesis.tsx new file mode 100644 index 0000000000..7ba042fcd8 --- /dev/null +++ b/client/src/components/Messages/SpeechSynthesis.tsx @@ -0,0 +1,41 @@ +import { useState, useEffect } from 'react'; + +function useSpeechSynthesis() { + const [isSpeechEnabled, setIsSpeechEnabled] = useState(false); + const [textToSpeak, setTextToSpeak] = useState(''); + + const synthesizeSpeech = (text) => { + setTextToSpeak(text); + }; + + const toggleSpeechSynthesis = () => { + setIsSpeechEnabled(!isSpeechEnabled); + console.log('Toggle Text-To-Speech', !isSpeechEnabled); + }; + + const handleKeyDown = (event) => { + if (event.shiftKey && event.altKey && event.key === 'P') { + toggleSpeechSynthesis(); + } + }; + + useEffect(() => { + window.addEventListener('keydown', handleKeyDown); + + return () => { + window.removeEventListener('keydown', handleKeyDown); + }; + }, [isSpeechEnabled]); + + useEffect(() => { + if (!isSpeechEnabled || !textToSpeak) return; + + const synth = window.speechSynthesis; + const utterance = new SpeechSynthesisUtterance(textToSpeak); + synth.speak(utterance); + }, [textToSpeak, isSpeechEnabled]); + + return { synthesizeSpeech, toggleSpeechSynthesis, isSpeechEnabled }; +} + +export default useSpeechSynthesis;