[Guide] How to make Text To Speech with React and Hugging Face
This article explains how to create a React application that can speech text, using the Hugging Face library (@huggingface/inference) and the Next.js framework.
Table of Contents
1. Use Case
2. Implementation
1. Use case
A default React JS project was created from scratch. In this project, we add the text “Hello World” on the page, with a “Speaker” icon positioned to its right.
Clicking on this icon triggers a voice to audibly speak the phrase “Hello World.”
2. Implementation
2.1 My previous blog introduced how to create a ReactJS project from scratch on macOS.
2.2 Add libraries to the project
yarn add @huggingface/inference react-icons
2.3 Add a component Speech.tsx
Please add a file Speech.tsx under src/components/Speech.tsx. The structure of the project is like following:
The Code looks like this:
import React from 'react';
import * as hf from '@huggingface/inference';
import { HiSpeakerWave } from "react-icons/hi2";
type SpeechProps = {
text: string;
};
const Speech: React.FC<SpeechProps> = ({ text }) => {
const speak = async () => {
const result = await hf.textToSpeech({
model: 'espnet/kan-bayashi_ljspeech_vits',
inputs: text || ''
});
// Create an Audio object and play the speech
const url = URL.createObjectURL(result);
const audio = new Audio(url);
audio.play();
};
return (
<div style={{ display: 'flex', alignItems: 'center' }}>
<div>{ text }</div>
<button style={{ marginLeft: '12px' }} onClick={speak}>
<HiSpeakerWave />
</button>
</div>
);
};
export default Speech;
2.4 Use component Speech in page.tsx
In the file src/app/page.tsx, define it as “use client” and import the component “Speech”.
Then insert “Speech” component in the first div and define the text as “Hello World”.
"use client";
import Speech from '@/components/Speech';
......
<Speech text="Hello world" />
2.5 Run
When the command “yarn dev” is executed in the project root from terminal, under http://localhost:3000 you will seen the screenshot at the begin of this post.
By clicking on the speak icon right to the “hello world”, the sound will be played.
I hope you enjoyed today’s content.
You are welcome to connect with me on medium and datatec.studio.
Your claps 👏 keep me continue writing high-quality articles. Thank you!