Hello All, In this React Native example, We will learn Text to speech example for React Native. In the last React Native tutorial, We had discussed How to use AsyncStorage in react native.
In this example, We will learn How to convert text to speech using react-native. We will use the react-native-tts library to convert text to speech.
Let’s discuss this React Native example in detail…
Steps to convert Text to speech example for React Native
- Create a new project
- Install npm dependency
- Write the logic
- Run
Create a new react native project using the following command
npx react-native init myapp
Install the required npm dependency using the following command
npm install --save react-native-tts
react-native link react-native-tts
Now, We will start writing our main logic.
Import the module using the following command
import Tts from 'react-native-tts';
Now, We will call the main method inside componentDidMount() as shown below
componentDidMount(){
Tts.speak('Hello world');
}
Full Source Code
import React, { Component } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Tts from 'react-native-tts';
class Home extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
Tts.speak('Hello world');
}
render() {
return (
<View style={styles.container}>
<Text style={styles.txt}> Text to speech in react native</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
alignItems: 'center',
justifyContent: 'center',
padding: 20
},
txt: {
fontSize: 20,
textAlign: 'center',
margin: 5
}
});
export default Home;
Call the Home component in App.js as shown below
import React, { Component } from 'react';
import { View, StyleSheet } from 'react-native';
import Home from './Home';
export default function App() {
return (
<View style={styles.container}>
<Home />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#ecf0f1',
padding: 8,
}
});
export default App;
npm run android
As soon as the application loads, The text we passed (‘Hello world’) will convert into speech.
In this way, We can able to convert Text to speech in react native application.