React Native Text to Speech Conversion
For text to speech conversion, we are using a very easy to integrate react-native-tts library which provides a Tts
component. Tts component provides the support of different voices and has listeners for each state as the reader started, finished, canceled.
To get Different Voices
const voices = await Tts.voices();
const availableVoices = voices
.filter(v => !v.networkConnectionRequired && !v.notInstalled)
.map(v => {
return { id: v.id, name: v.name, language: v.language };
});
Add different Listeners
Tts.addEventListener(
'tts-start',
(_event) => setTtsStatus('started')
);
Tts.addEventListener(
'tts-finish',
(_event) => setTtsStatus('finished')
);
Tts.addEventListener(
'tts-cancel',
(_event) => setTtsStatus('cancelled')
);
Now let’s get started with the example and see how to convert text to speech.
To Make a React Native App
Getting started with React Native cli
npm install -g react-native-cli
Run the following commands to create a new React Native project
react-native init ProjectName
Installation of Dependency
To use Tts
component we have to install react-native-tts
dependency. To install the dependency open the terminal and jump into your project
cd ProjectName
Now install the dependency
npm install react-native-tts --save
For this example, we are using Slider
component provided by react-native-community
to control the pitch and speed of voice so we will also have to install the following dependency for the same
npm install @react-native-community/slider --save
CocoaPods Installation
need to install pods. In this example, we need to install the pods for react-native-tts
and Slider
.
Please use the following command to install CocoaPods
cd ios && pod install && cd ..
Code to Convert Text to Speech
Now Open App.js in any code editor and replace the code with the following code.
To Run the React Native App
Open the terminal again and jump into your project using.
cd ProjectName
To run the project on an Android Virtual Device or on real debugging device
react-native run-android
or on the iOS Simulator by running (macOS only)
react-native run-ios
If you have any doubt feel free to comment here.
Hope you liked it
Thanks.