Speech2TextJs is a lightweight and flexible library for developers looking to integrate speech-to-text functionality into their projects. It uses modern speech recognition technologies to provide accurate transcriptions of spoken language. Whether you're
npm install speech2textjsbash
npm install speech2textjs
`
Basic Setup
You can use the useSpeechToText hook to start listening and convert speech into text. Here's an example of how to use it in your React component:
Usage
`javascript
import React, { useState } from 'react';
import { Button } from 'your-ui-library'; // Customize as per your UI library
import { Mic } from 'lucide-react'; // Optional, use for icon
import useSpeechToText from 'speech2text'; // Import the hook
function RecordAnswerSection() {
const [userAnswer, setUserAnswer] = useState("");
const { isListening, transcript, startListening, stopListening } = useSpeechToText({ continuous: true });
const startStopListening = () => {
if (isListening) {
stopVoiceInput();
} else {
startListening();
}
};
const stopVoiceInput = () => {
setUserAnswer(prev => prev + " " + transcript);
stopListening();
};
useEffect(() => {
if (isListening) {
const newText = transcript.replace(previousTranscript.current, "").trim();
if (newText) {
setUserAnswer(prev => prev + (newText ? " " + newText : ""));
previousTranscript.current = transcript;
}
}
}, [transcript, isListening]);
return (
{userAnswer}
disabled={isListening}
value={userAnswer}
onChange={(e) => { setUserAnswer(e.target.value); }}
/>
);
}
export default RecordAnswerSection;
`
Example with Custom Options
You can customize the options when using the hook, like so:
Customization
`javascript
const { isListening, transcript, startListening, stopListening } = useSpeechToText({
continuous: true,
interimResults: true,
lang: 'en-GB',
});
``