DEV Community

Ajmal Hasan
Ajmal Hasan

Posted on

React Native Text To Speech

Exploring react-native-tts: A Comprehensive Guide to Text-to-Speech in React Native

Text-to-Speech (TTS) technology is transforming how we interact with mobile applications by converting written text into spoken words. If you're developing a React Native application and want to incorporate TTS functionality, react-native-tts is a popular library that makes this integration straightforward. In this guide, we'll explore how to use react-native-tts, covering installation, basic usage, and advanced features.


What is react-native-tts?

react-native-tts is a Text-to-Speech library for React Native that allows developers to add speech synthesis capabilities to their apps. It supports both Android and iOS, making it a versatile choice for cross-platform development. With react-native-tts, you can convert text to speech, control speech parameters like pitch and rate, and handle various speech events.


Installation

To get started with react-native-tts, you'll need to install it via npm or yarn. Open your terminal and run:

npm install react-native-tts
Enter fullscreen mode Exit fullscreen mode

or

yarn add react-native-tts
Enter fullscreen mode Exit fullscreen mode

Usage

a) Create a file ttsListeners.jsx:

import Tts from 'react-native-tts';

// Function to initialize Text-to-Speech (TTS) settings and listeners
export const initializeTtsListeners = async () => {
  // Check the initialization status of the TTS engine
  Tts.getInitStatus().then(
    (e) => {
      console.log('ALL OK TTS ✅'); // TTS is initialized successfully
    },
    (err) => {
      // If there is no TTS engine installed, request to install one
      if (err.code === 'no_engine') {
        console.log('NO ENGINE TTS ✅');
        Tts.requestInstallEngine();
      }
    }
  );

  // The following commented-out code can be used to list available voices and set a default voice
  // const voices = await Tts.voices()
  // console.log(voices)
  // Tts.setDefaultVoice('com.apple.speech.synthesis.voice.Albert')

  // Set the default speaking rate. Lower values are slower, and higher values are faster
  Tts.setDefaultRate(0.3, true);

  // Ignore the silent switch on the device, allowing TTS to play even if the device is set to silent
  Tts.setIgnoreSilentSwitch('ignore');

  // Set the default pitch. Lower values result in a lower pitch, and higher values in a higher pitch
  Tts.setDefaultPitch(0.7);

  // Set up listeners for various TTS events

  // Listener for when TTS starts speaking
  Tts.addEventListener('tts-start', (event) => {
    console.log('TTS Started: ', event);
  });

  // Listener for TTS progress (triggered repeatedly while speaking)
  Tts.addEventListener('tts-progress', (event) => {
    // console.log('TTS progress: ', event) // Uncomment to log progress events
  });

  // Listener for when TTS finishes speaking
  Tts.addEventListener('tts-finish', (event) => {
    console.log('TTS finished: ', event);
  });

  // Listener for when TTS is canceled
  Tts.addEventListener('tts-cancel', (event) => {
    console.log('TTS Cancel: ', event);
  });
};

// Function to play a message using TTS
export const playTTS = async (message) => {
  // Ensure TTS is initialized before speaking
  Tts.getInitStatus().then(
    (e) => {
      console.log('ALL OK TTS ✅'); // TTS is initialized successfully
    },
    (err) => {
      // If there is no TTS engine installed, request to install one
      if (err.code === 'no_engine') {
        console.log('NO ENGINE TTS ✅');
        Tts.requestInstallEngine();
      }
    }
  );

  // Use TTS to speak the provided message
  Tts.speak(message);
};

Enter fullscreen mode Exit fullscreen mode

b) Now initialise and use it:

App.jsx

import { StyleSheet, Text, View } from 'react-native';
import React from 'react';
import { initializeTtsListeners } from './utils/ttsListners';

const App = () => {
  useEffect(() => {
    initializeTtsListeners();

    setTimeout(() => {
      playTTS('Hello World! This is text to speech implementation, Keep Coding!!!.'); // or Tts.speak(message)

    }, 1000);
  }, []);

  return (
    <View>
      <Text>App</Text>
    </View>
  );
};

export default App;

const styles = StyleSheet.create({});

Enter fullscreen mode Exit fullscreen mode

Conclusion

react-native-tts is a powerful and flexible library for adding text-to-speech functionality to your React Native applications. With its easy setup, event handling, and advanced features, you can enhance user experience by incorporating natural language interactions. Experiment with different configurations and make the most of TTS to create engaging and accessible applications.

Top comments (3)

Collapse
 
greenersoft profile image
GreenerSoft

All this sounds very complicated, when the basic SpeechSynthesis Javascript API is so easy to use.

Collapse
 
ajmal_hasan profile image
Ajmal Hasan

I guess this won't work for react native apps

Collapse
 
greenersoft profile image
GreenerSoft

You're probably right, I was talking about the web version.