Home > Web Front-end > JS Tutorial > body text

React Native Text To Speech

WBOY
Release: 2024-08-31 06:31:36
Original
398 people have browsed it

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
Copy after login

or

yarn add react-native-tts
Copy after login

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);
};

Copy after login

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({});

Copy after login

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.

The above is the detailed content of React Native Text To Speech. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!