36
Text-to-speech in ReactJS
Hello Guys today i am going to show you how you can convert your text into speech using "react-speech-kit".
This module will convert your text into voice and the voice will be played in your web application.This module is very cool and helps you to implement text-to-speech very easily as compared to vanilla javascript.
Lets get started....
Firstly run this command into your terminal to install this module
npm i react-speech-kit
Then import the module
import { useSpeechSynthesis } from "react-speech-kit";
Then declare a variable named speak inside curly braces and assign the value of react useSpeechSynthesis() hook.
const { speak } = useSpeechSynthesis();
Then create a button which will have onClick method which will call an arrow function which have speak function and we will pass the text inside it to convert the text into speech.
<button class='btn btn-primary btn-lg'
onClick={() => speak({ text: 'Hello React Js' })}>
Speak
</button>
When you will click this button there will a voice saying "Hello React Js".
You can also give the input text using form and then convert the text to speech
Example -
import React from "react";
import { useSpeechSynthesis } from "react-speech-kit";
const Speech = () => {
const [value, setValue] = React.useState("");
const { speak } = useSpeechSynthesis();
return (
<div className="speech">
<div className="group">
<h2>Text To Speech Converter Using React Js</h2>
</div>
<div className="group">
<textarea
rows="10"
value={value}
onChange={(e) => setValue(e.target.value)}
></textarea>
</div>
<div className="group">
<button onClick={() => speak({ text: value })}>
Speech
</button>
</div>
</div>
);
};
export default Speech;
When you write something into the textarea and click the speech button the text written inside textarea will be converted to speech and a voice will be played saying the text you have written inside textarea.
36