How to Make Your Expo (React Native) App Talk (TTS)

Thanks to the expo-speech library, we can easily add text-to-speech to our apps. The best part is it's supported across multiple platforms, including Android devices and emulators, iOS devices and simulators, and the web.

First, make sure you have the Expo CLI installed on your machine. Then, to add TTS functionality to your Expo app, run the following command:

npx expo install expo-speech

For those working on a bare React Native project, additional installation steps may be required as outlined in the library's documentation.

Once installed, you can use your app's expo-speech library.

Here’s a simple example to get you started:

import * as React from 'react';
import { View, StyleSheet, Button } from 'react-native';
import * as Speech from 'expo-speech';

export default function App() {
  const speak = () => {
    const words = 'Hello, world!';
    Speech.speak(words);
  };

  return (
    <View style={styles.container}>
      <Button title="Press me and listen!" onPress={speak} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#a5f3fc',
    padding: 16,
  },
});

This code snippet demonstrates how to create a button that, when pressed, uses the device's TTS engine to say "Hello, world!".

More options

The expo-speech library also supports a variety of advanced features, including adjusting the pitch and rate of speech, selecting specific voices, and handling events such as speech start, finish, and error handling. These options can be passed to the Speech.speak method via an options object, allowing for a customizable TTS experience.

Speech.speak(text, {
  language: 'en-US',
  pitch: 1.0,
  rate: 1.0,
  voice: 'identifier',
  volume: 1.0,
  onDone: () => { console.log('Finished speaking.'); },
  onError: (error) => { console.error('An error occurred:', error); },
});

As you can see, with just a few lines of code, your app can speak to your users, enhancing their experience and interaction with your application.

React NativeExpo
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.