New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

react-text-to-speech

Package Overview
Dependencies
Maintainers
1
Versions
121
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-text-to-speech

An easy to use react component for the Web Speech API.

  • 0.8.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
3.1K
increased by0.23%
Maintainers
1
Weekly downloads
 
Created
Source

react-text-to-speech

An easy to use react component for the Web Speech API.

It is as easy as to import a React component!

Features

  • Text-to-speech
  • Easy to use
  • Stops speech instance on page reload.
  • Highlights words as they are read.
  • Handles multiple speech instances easily. See Advanced Usage
  • Fully Customizable. See usage with FaC

Installation

To install react-text-to-speech

  # with npm:
  npm install react-text-to-speech --save

  # with yarn:
  yarn add react-text-to-speech

  # with pnpm:
  pnpm add react-text-to-speech

  # with bun:
  bun add react-text-to-speech

Usage

When you use the <Speech> component of react-text-to-speech, initially the user will see the startBtn and when the user clicks on it, the speech instance will start and the user will see the pauseBtn which can be used to pause the speech instance. The user will also see the stopBtn which can be used to stop the speech instance at any moment.

Basic Usage
import React from "react";
import Speech from "react-text-to-speech";

export default function App() {
  return <Speech text="This library is awesome!" />;
}
Advanced Usage

Let's assume that you fetch news from any News API and the API returns 3 news in response as shown below. Now if the user clicks on startBtn of #1 news (assuming # as id) and then clicks on startBtn on #2 news before the speech instance of #1 news ends, then react-text-to-speech will not just stop the #1 news speech instance and start the #2 news speech instance, but will also convert the pauseBtn of #1 news to startBtn, thus avoiding any inconsistency.

import React from "react";
import Speech from "react-text-to-speech";

export default function App() {
  // 'news' holds response from some News API
  const news = [
    { id: "1", title: "First random title", desc: "First random description" },
    { id: "2", title: "Second random title", desc: "Second random description" },
    { id: "3", title: "Third random title", desc: "Third random description" },
  ];

  return (
    <>
      {news.map(({ id, title, desc }) => (
        <div key={id}>
          <h4>{title}</h4>
          <div>{desc}</div>
          <Speech text={`${title}. ${desc}`} />
        </div>
      ))}
    </>
  );
}
Highlight Text

If highlightText prop to true, the words in the text will be highlighted as they are spoken. <HighlightedText> component exported by react-text-to-speech can be used to accomplish this purpose.

NOTE: id of both <Speech> and <HighlightedText> should be same to link them together.

import React from "react";
import Speech, { HighlightedText } from "react-text-to-speech";

export default function App() {
  return (
    <>
      <Speech
        id="unique-id"
        highlightText={true}
        highlightProps={{ style: { color: "white", backgroundColor: "blue" } }}
        text={
          <div>
            <span>This library is awesome!</span>
            <div>
              <div>
                <span>It can also read and highlight </span>
                <span>nested text... </span>
                <span>
                  <span>upto </span>
                  <span>
                    <span>any level.</span>
                  </span>
                </span>
              </div>
            </div>
          </div>
        }
      />
      <HighlightedText id="unique-id" />
    </>
  );
}
Partial Customization

Use props provided by <Speech> component to customize it.

import React from "react";
import Speech from "react-text-to-speech";

export default function App() {
  const startBtn = <button className="my-start-btn">Start Speech</button>;
  const pauseBtn = <button className="my-pause-btn">Pause Speech</button>;
  const stopBtn = <button className="my-stop-btn">Stop Speech</button>;

  return (
    <Speech
      text="This is a partially customized speech component."
      pitch={1.5}
      rate={2}
      volume={0.5}
      voiceURI="Microsoft Heera - English (India)"
      startBtn={startBtn}
      pauseBtn={pauseBtn}
      stopBtn={stopBtn}
      props={{ title: "React Text-To-Speech Component" }}
      onError={() => console.error("Browser not supported!")}
    />
  );
}
Full Customization

Use Function as Children(FaC) to fully customize the <Speech> component.

import React from "react";
import Speech from "react-text-to-speech";

export default function App() {
  return (
    <Speech
      text="This is a fully customized speech component."
      pitch={1.5}
      rate={2}
      volume={0.5}
      voiceURI="Microsoft Heera - English (India)"
      onError={() => console.error("Browser not supported!")}
    >
      {({ speechStatus, start, pause, stop }) => (
        <YourCustomComponent>
          {speechStatus !== "started" && (
            <button className="my-start-btn" onClick={start}>
              Start Speech
            </button>
          )}
          {speechStatus === "started" && (
            <button className="my-pause-btn" onClick={pause}>
              Pause Speech
            </button>
          )}
          <button className="my-stop-btn" onClick={stop}>
            Stop Speech
          </button>
        </YourCustomComponent>
      )}
    </Speech>
  );
}

Speech Component API Reference

Here is the full API for the <Speech> component, these properties can be set on an instance of Speech:

ParameterTypeRequiredDefaultDescription
textstring | JSX.ElementYes-It contains the text to be spoken when startBtn is clicked.
pitchnumber (0 to 2)No1The pitch at which the utterance will be spoken.
ratenumber (0.1 to 10)No1The speed at which the utterance will be spoken.
volumenumber (0 to 1)No1The volume at which the utterance will be spoken.
langstringNo-The language in which the utterance will be spoken.
voiceURIstring | string[]No-The voice using which the utterance will be spoken. If provided an array, further voices will be used as fallback if initial voices are not found. See possible values here.
startBtnButtonNo<HiVolumeUp />Button to start the speech instance.
pauseBtnButtonNo<HiVolumeOff />Button to pause the speech instance.
stopBtnButtonNo<HiMiniStop />Button to stop the speech instance.
useStopOverPausebooleanNonavigator.userAgentData.mobileWhether the controls should display stopBtn instead of pauseBtn. In Android devices, SpeechSynthesis.pause() behaves like SpeechSynthesis.cancel(). See details
highlightTextbooleanNofalseWhether the words in the text should be highlighted as they are read or not.
highlightPropsReact.DetailedHTMLPropsNo{ style: { fontWeight: "bold" } }Props to customise the highlighted word.
onErrorFunctionNo() => alert('Browser not supported! Try some other browser.')Function to be executed if browser doesn't support Web Speech API.
propsReact.DetailedHTMLPropsNo-Props to customize the <Speech> component.
childrenChildrenNo-See usage with FaC

Types

Button
type Button = JSX.Element | string | null;
Children
import { ReactNode } from "react";
type SpeechStatus = "started" | "paused" | "stopped";
type ChildrenOptions = {
  speechStatus?: SpeechStatus;
  start?: Function;
  pause?: Function;
  stop?: Function;
};
type Children = (childrenOptions: ChildrenOptions) => ReactNode;

Author

Sahil Aggarwal

Contributors

Keywords

FAQs

Package last updated on 04 Feb 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc