speech2textjs

1.0.2 • Public • Published

Speech2textJS

Speech2text is a simple React hook for converting speech into text in real time. It uses the Web Speech API (webkitSpeechRecognition) to provide speech recognition functionality, allowing you to integrate voice-to-text in your React applications with minimal effort.

Installation

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

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 (
    <div>
      <Button className="my-10" onClick={startStopListening}>
        {isListening ? <h2><Mic /> Recording...</h2> : "Record Answer"}
      </Button>
      <Button onClick={() => { console.log(userAnswer); }}>
        Show Recorded Answer
      </Button>
      <h2>{userAnswer}</h2>
      <textarea
        disabled={isListening}  
        value={userAnswer}
        onChange={(e) => { setUserAnswer(e.target.value); }}  
      />
    </div>
  );
}

export default RecordAnswerSection;

Example with Custom Options You can customize the options when using the hook, like so:

Customization

const { isListening, transcript, startListening, stopListening } = useSpeechToText({
  continuous: true,
  interimResults: true,
  lang: 'en-GB',
});

Readme

Keywords

Package Sidebar

Install

npm i speech2textjs

Weekly Downloads

0

Version

1.0.2

License

ISC

Unpacked Size

5.47 kB

Total Files

3

Last publish

Collaborators

  • rajatparihar26