Create SpeechSynthesis.tsx

This commit is contained in:
bsu3338 2023-08-09 00:57:57 -05:00 committed by GitHub
parent 252325dcda
commit f9ed2ad8db
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -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;