React Native Text to Speech Conversion
This is an example to show how to do Text to Speech Conversion with Natural Voices in React Native – Text Reader. As the name suggests we are going to see how can you implement a text reader feature in your React Native App. We are going to use the TTS engine to convert our Text into Speech. This is a very popular feature nowadays. If you have observed each and every newspaper or content provider application are implementing Text to Speech conversion feature and getting the attention of their customer too.
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')
);
In this example, we are going to make a screen with 2 sliders to control the speed and pitch of the voice. We will have a TextInput to get the text to read and a button to start reading. We will also have a list of different voices and languages below which will help us to try different combinations.
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 will help you to know more about the way you can make a React Native project. We are going to use react native command line interface to make our React Native App.
If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:
npm uninstall -g react-native-cli @react-native-community/cli
Run the following commands to create a new React Native project
npx react-native init ProjectName
If you want to start a new project with a specific React Native version, you can use the --version argument:
npx react-native init ProjectName --version X.XX.X
Note If the above command is failing, you may have old version of react-native
or react-native-cli
installed globally on your pc. Try uninstalling the cli and run the cli using npx.
This will make a project structure with an index file named App.js in your project directory.
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
Please use the following command to install CocoaPods
npx pod-install
Code to Convert Text to Speech
Now Open App.js in any code editor and replace the code with the following code.
App.js
// Text to Speech Conversion with Natural Voices in React Native
// https://aboutreact.com/react-native-text-to-speech/
// import React in our code
import React, {useState, useEffect} from 'react';
// import all the components we are going to use
import {
SafeAreaView,
StyleSheet,
Text,
View,
FlatList,
TextInput,
Keyboard,
TouchableOpacity,
} from 'react-native';
// import slider for the tuning of pitch and speed
import Slider from '@react-native-community/slider';
// import Tts Text to Speech
import Tts from 'react-native-tts';
const App = () => {
const [voices, setVoices] = useState([]);
const [ttsStatus, setTtsStatus] = useState('initiliazing');
const [selectedVoice, setSelectedVoice] = useState(null);
const [speechRate, setSpeechRate] = useState(0.5);
const [speechPitch, setSpeechPitch] = useState(1);
const [
text,
setText
] = useState('Enter Text like Hello About React');
useEffect(() => {
Tts.addEventListener(
'tts-start',
(_event) => setTtsStatus('started')
);
Tts.addEventListener(
'tts-finish',
(_event) => setTtsStatus('finished')
);
Tts.addEventListener(
'tts-cancel',
(_event) => setTtsStatus('cancelled')
);
Tts.setDefaultRate(speechRate);
Tts.setDefaultPitch(speechPitch);
Tts.getInitStatus().then(initTts);
return () => {
Tts.removeEventListener(
'tts-start',
(_event) => setTtsStatus('started')
);
Tts.removeEventListener(
'tts-finish',
(_event) => setTtsStatus('finished'),
);
Tts.removeEventListener(
'tts-cancel',
(_event) => setTtsStatus('cancelled'),
);
};
}, []);
const initTts = async () => {
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};
});
let selectedVoice = null;
if (voices && voices.length > 0) {
selectedVoice = voices[0].id;
try {
await Tts.setDefaultLanguage(voices[0].language);
} catch (err) {
//Samsung S9 has always this error:
//"Language is not supported"
console.log(`setDefaultLanguage error `, err);
}
await Tts.setDefaultVoice(voices[0].id);
setVoices(availableVoices);
setSelectedVoice(selectedVoice);
setTtsStatus('initialized');
} else {
setTtsStatus('initialized');
}
};
const readText = async () => {
Tts.stop();
Tts.speak(text);
};
const updateSpeechRate = async (rate) => {
await Tts.setDefaultRate(rate);
setSpeechRate(rate);
};
const updateSpeechPitch = async (rate) => {
await Tts.setDefaultPitch(rate);
setSpeechPitch(rate);
};
const onVoicePress = async (voice) => {
try {
await Tts.setDefaultLanguage(voice.language);
} catch (err) {
// Samsung S9 has always this error:
// "Language is not supported"
console.log(`setDefaultLanguage error `, err);
}
await Tts.setDefaultVoice(voice.id);
setSelectedVoice(voice.id);
};
const renderVoiceItem = ({item}) => {
return (
<TouchableOpacity
style={{
backgroundColor: selectedVoice === item.id ?
'#DDA0DD' : '#5F9EA0',
}}
onPress={() => onVoicePress(item)}>
<Text style={styles.buttonTextStyle}>
{`${item.language} - ${item.name || item.id}`}
</Text>
</TouchableOpacity>
);
};
return (
<SafeAreaView style={styles.container}>
<View style={styles.container}>
<Text style={styles.titleText}>
Text to Speech Conversion with Natural Voices
</Text>
<View style={styles.sliderContainer}>
<Text style={styles.sliderLabel}>
{`Speed: ${speechRate.toFixed(2)}`}
</Text>
<Slider
style={styles.slider}
minimumValue={0.01}
maximumValue={0.99}
value={speechRate}
onSlidingComplete={updateSpeechRate}
/>
</View>
<View style={styles.sliderContainer}>
<Text style={styles.sliderLabel}>
{`Pitch: ${speechPitch.toFixed(2)}`}
</Text>
<Slider
style={styles.slider}
minimumValue={0.5}
maximumValue={2}
value={speechPitch}
onSlidingComplete={updateSpeechPitch}
/>
</View>
<Text style={styles.sliderContainer}>
{`Selected Voice: ${selectedVoice || ''}`}
</Text>
<TextInput
style={styles.textInput}
onChangeText={(text) => setText(text)}
value={text}
onSubmitEditing={Keyboard.dismiss}
/>
<TouchableOpacity
style={styles.buttonStyle}
onPress={readText}>
<Text style={styles.buttonTextStyle}>
Click to Read Text ({`Status: ${ttsStatus || ''}`})
</Text>
</TouchableOpacity>
<Text style={styles.sliderLabel}>
Select the Voice from below
</Text>
<FlatList
style={{width: '100%', marginTop: 5}}
keyExtractor={(item) => item.id}
renderItem={renderVoiceItem}
extraData={selectedVoice}
data={voices}
/>
</View>
</SafeAreaView>
);
};
export default App;
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
padding: 5,
},
titleText: {
fontSize: 22,
textAlign: 'center',
fontWeight: 'bold',
},
buttonStyle: {
justifyContent: 'center',
marginTop: 15,
padding: 10,
backgroundColor: '#8ad24e',
},
buttonTextStyle: {
color: '#fff',
textAlign: 'center',
},
sliderContainer: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
width: 300,
padding: 5,
},
sliderLabel: {
textAlign: 'center',
marginRight: 20,
},
slider: {
flex: 1,
},
textInput: {
borderColor: 'gray',
borderWidth: 1,
color: 'black',
width: '100%',
textAlign: 'center',
height: 40,
},
});
To Run the React Native App
Open the terminal again and jump into your project using.
cd ProjectName
1. Start Metro Bundler
First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command:
npx react-native start
Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.
2. Start React Native Application
To run the project on an Android Virtual Device or on real debugging device:
npx react-native run-android
or on the iOS Simulator by running (macOS only)
npx react-native run-ios
Error Possibility
If you face any issues while running the Android app, you can make the following changes
In project/build.gradle
1. Update minSdkVersion to 23
2. Add kotlin_version in buildscript >> ext and a dependency in buildscript >> dependencies
buildscript {
ext {
...
minSdkVersion = 21
...
kotlin_version = '1.5.10'
}
repositories {
...
}
dependencies {
...
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version")
...
}
}
3. Add following in project/app/build.gradle
apply plugin: "kotlin-android"
apply plugin: "kotlin-android-extensions"
Output Screenshots
This was text to speech conversion with natural voices in React Native. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!
Hope you liked it. 🙂
This is done for me ……..
Thanks a lot,i m happy that today i can learned something great……
Hey,
Can you please update this code with react native latest version as i see this code is old using class not functional component.
Updated for the same
Thanks alot man… you are great !!
Thank you is so awesome
Actually in Android i am able toh set default engine as google but in ios i can’t set that in this library do you have amy solution for that or any other library i can use for that
This is just the bridge to list the native tts functionality so unable to do that. Tried but unable to find any famous library to do that.
Good morning. I am some trouble using React native Text to speech library.
I would select different italian voices than the default voice (ALICE). Is it possible ?
In the list of default voices there is only ALICE, but on the iphone (IO14+) there are also LUCA and FEDERICA.
How can i fix this problem ?
THANKS A LOT
Hey! This library does not provide any special voice it just lists the voices supported by the phone and will play that voice, can’t do something special 😐