Java/Android - How to implement Text-to-Speech (TTS)

Java/Android – How to implement Text-to-Speech (TTS)

Nowadays Text-to-Speech (TTS) finds usage in a wide range of areas. Need someone to read your book? Driving with GPS? Communicating with voice assistants like Siri and Alexa? Supporting people with visual/reading impairments? Programming your own robot? Whatever reason you have, I will show you how to implement Text-to-Speech (TTS) in Java/Android.

Java/Android – How to implement Text-to-Speech (TTS)

Welcome to a new episode of our Android coverage. In our last episode, we spoke about device vibration.

Before we start, open a new empty project in Android Studio and call it Text2SpeechTutorial. For this feature, we don’t need any permissions or special dependencies.

First, let’s modify the activity_mail.xml. We just want to add an EditText where the user can enter the text that will be converted and a Button that will start the conversion:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/texttoconvert"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginBottom="256dp"
        android:hint="Enter Text2Speech"
        android:textAlignment="center"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/convertbutton"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginTop="60dp"
        android:text="Click To Convert"
        app:layout_constraintBottom_toTopOf="@+id/texttoconvert"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.816" />
</androidx.constraintlayout.widget.ConstraintLayout>

Now onto the MainActivity.java – here we will do 3 things.

First, we will create a new TextToSpeech object where we can set our language:

TextToSpeech t1;

 t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
            public void onInit(int status) {
                if (status != TextToSpeech.ERROR) {
                    t1.setLanguage(Locale.GERMAN);
                }
            }
        });

Our second step will be setting an OnClickListener for our Button and making sure we get a valid input:

Button convertbutton;

convertbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                edit = findViewById(R.id.texttoconvert);
                String text2speech = edit.getText().toString();
                if (text2speech == null || "".equals(text2speech)) {
                    text2speech = "Please enter valid Text";
                    t2s.speak(text2speech, TextToSpeech.QUEUE_FLUSH, null);
                } else {
                    t2s.speak(text2speech, TextToSpeech.QUEUE_FLUSH, null);
                }
            }
        });

and lastly, we want to make sure our TextToSpeech object is stopped and closed when our App goes into the background:

@Override
  protected void onPause() {
      if (t2s != null) {
          t2s.stop();
          t2s.shutdown();
      }
      super.onPause();
  }

So putting it all together our MainActivity.java should look like this:

public class MainActivity extends AppCompatActivity {

    TextToSpeech t2s;
    EditText edit;
    Button convertbutton;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        convertbutton = findViewById(R.id.convertbutton);
        t2s = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
            public void onInit(int status) {
                if (status != TextToSpeech.ERROR) {
                    t2s.setLanguage(Locale.GERMAN);
                }
            }
        });
        convertbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                edit = findViewById(R.id.texttoconvert);
                String text2speech = edit.getText().toString();
                if (text2speech == null || "".equals(text2speech)) {
                    text2speech = "Please enter valid Text";
                    t2s.speak(text2speech, TextToSpeech.QUEUE_FLUSH, null);
                } else {
                    t2s.speak(text2speech, TextToSpeech.QUEUE_FLUSH, null);
                }
            }
        });
    }

    @Override
    protected void onPause() {
        if (t2s != null) {
            t2s.stop();
            t2s.shutdown();
        }
        super.onPause();
    }
}

And that’s it! Run your app and try it. I recommend you change the setLanguage() attribute to the language you want to convert. It will convert anyways but you will hear a different accent and pronunciation.

Conclusion

Adding this little feature takes only a couple of minutes and considering the fact that there are so many situations in which Text-To-Speech (TTS) can/must be implemented I would say that every Android dev should play around with it at some point!

If you want to read more about Text-to-Speech (TTS) please visit this link.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: