Text to speech example for React Native

Share the post

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 project
  • Create a new react native project using the following command

    npx react-native init myapp
    

  • Install npm dependency
  • Install the required npm dependency using the following command

    npm install --save react-native-tts
    react-native link react-native-tts
    

  • Write the logic
  • 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;
    
    

  • Run
  • Run the react native application using the following command

    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.

    Leave a Comment