DEV Community

Cover image for Text-to-speech in ReactJS
Mysterio
Mysterio

Posted on • Updated on

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....

Installation -

Firstly run this command into your terminal to install this module

npm i react-speech-kit
Enter fullscreen mode Exit fullscreen mode

Then import the module

import { useSpeechSynthesis } from "react-speech-kit";
Enter fullscreen mode Exit fullscreen mode

Then declare a variable named speak inside curly braces and assign the value of react useSpeechSynthesis() hook.

 const { speak } = useSpeechSynthesis();
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

When you will click this button there will a voice saying "Hello React Js".

Using this with From -

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;
Enter fullscreen mode Exit fullscreen mode

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.

THANK YOU FOR READING THIS POST AND IF YOU FIND ANY MISTAKE OR WANTS TO GIVE ANY SUGGESTION PLEASE MENTION IT IN THE COMMENT SECTION.

You can help me by some donation at the link below Thank you πŸ‘‡πŸ‘‡

β˜• - https://www.buymeacoffee.com/waaduheck

Also check these post

https://dev.to/shubhamtiwari909/best-vs-code-extensions-for-web-development-2lk3

https://dev.to/shubhamtiwari909/auto-sizing-columns-in-css-grid-n16

https://dev.to/shubhamtiwari909/hover-effects-with-hovercss-52fd

https://dev.to/shubhamtiwari909/python-data-science-libraries-for-beginners-1bjp

Discussion (0)