App.jsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 |
import React, { useState, useEffect } from "react"; import { useSpeechSynthesis, useSpeechRecognition } from "react-speech-kit"; import "./App.css"; // Optional CSS for styling function App() { const [text, setText] = useState(""); const [recognizedText, setRecognizedText] = useState(""); const [voice, setVoice] = useState(null); const { speak, cancel, speaking, voices, supported: synthesisSupported } = useSpeechSynthesis(); const { listen, stop, listening, supported: recognitionSupported, } = useSpeechRecognition({ onResult: (result) => { setRecognizedText(result); }, onEnd: () => console.log("Speech recognition stopped"), }); useEffect(() => { if (voices.length > 0) { setVoice(voices[0]); } }, [voices]); const handleSpeak = () => { if (text) { speak({ text, voice }); } }; return ( <div className="container"> <h1 className="title">React Speech Kit Demo</h1> <div className="section"> <div className="half"> <h2>Text-to-Speech</h2> {synthesisSupported ? ( <> <label className="label">Enter Text:</label> <textarea className="textarea" rows="4" value={text} onChange={(e) => setText(e.target.value)} /> <label className="label">Select Voice:</label> <select className="select" value={voice?.name} onChange={(e) => setVoice(voices.find((v) => v.name === e.target.value)) } > {voices.map((v, idx) => ( <option key={idx} value={v.name}> {v.name} ({v.lang}) </option> ))} </select> <div className="button-group"> <button onClick={handleSpeak} disabled={speaking}> {speaking ? "Speaking..." : "Speak"} </button> <button onClick={cancel} className="danger"> Cancel </button> </div> </> ) : ( <div className="alert">Speech Synthesis is not supported.</div> )} </div> <div className="half"> <h2>Speech-to-Text</h2> {recognitionSupported ? ( <> <label className="label">Recognized Text:</label> <textarea className="textarea" rows="4" value={recognizedText} readOnly /> <div className="button-group"> <button onMouseDown={() => listen({ interimResults: true })} onMouseUp={stop} disabled={listening} > {listening ? "Listening..." : "Start Listening"} </button> <button onClick={stop} className="danger"> Stop </button> </div> {listening && <div className="alert">Go ahead, I'm listening...</div>} </> ) : ( <div className="alert">Speech Recognition is not supported.</div> )} </div> </div> </div> ); } export default App; |