Android Text to Speech Example

Android is providing a cool feature (from Android 1.6) called Text to Speech (TTS) or speech synthesis which speaks the text in different languages.

This tutorial is about how to work with android text to speech or android speech synthesis. It also includes changing the language type, speech pitch and speech rate.

Creating new Project

1. Create a new project by going to File New Android Project, fill the required details and then click on finish.

2. The below layout file consist of a textView , an input field and a button to trigger a event that will take text from input field and speaks out.

activity_main.xml

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv_text_to_speech"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/margin_50dp"
        android:gravity="center"
        android:text="@string/text_to_speech"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="@dimen/textSize_30sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/edt_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/margin_10dp"
        android:layout_marginEnd="@dimen/margin_10dp"
        android:layout_marginTop="@dimen/margin_30dp"
        android:ems="10"
        android:background="@drawable/background"
        android:hint="@string/enter_some_text_to_speak"
        android:padding="@dimen/padding_12dp"
        app:layout_constraintEnd_toEndOf="@+id/tv_text_to_speech"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="@+id/tv_text_to_speech"
        app:layout_constraintTop_toBottomOf="@+id/tv_text_to_speech" />

    <Button
        android:id="@+id/btn_speak"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/margin_30dp"
        android:background="@color/colorPrimary"
        android:text="@string/speak_text"
        android:padding="@dimen/padding_12dp"
        android:textStyle="bold"
        android:textSize="@dimen/textSize_18sp"
        android:textColor="@android:color/white"
        app:layout_constraintEnd_toEndOf="@+id/edt_text"
        app:layout_constraintStart_toStartOf="@+id/edt_text"
        app:layout_constraintTop_toBottomOf="@+id/edt_text" />

</androidx.constraintlayout.widget.ConstraintLayout>

3. Open MainActivity.java, implement it from TextToSpeech.OnInitListener and add the below code.

MainActivity.java

package com.c1ctech.texttospeechdemo;

import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.util.Locale;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {

    EditText edtText;
    Button btnSpeak;
    TextToSpeech tts;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //get views by id
        edtText = findViewById(R.id.edt_text);
        btnSpeak = findViewById(R.id.btn_speak);

        tts = new TextToSpeech(this, this);

        // button on click event
        btnSpeak.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //get edt value
                String text = edtText.getText().toString();

                tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, "abc");
            }
        });

    }

    @Override
    public void onInit(int status) {

        if (status == TextToSpeech.SUCCESS) {

            int result = tts.setLanguage(Locale.US);

            if (result == TextToSpeech.LANG_MISSING_DATA
                    || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                Log.e("TTS", "This Language is not supported");
            }
        } else {
            Log.e("TTS", "Initilization Failed!");
        }

    }

    @Override
    public void onDestroy() {
        //don't forget to shutdown tts
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
        super.onDestroy();
    }

}

In the above code,

onInit(): Called to signal the completion of the TextToSpeech engine initialization. Here, you have to specify the properties for TextToSpeech object , such as its language ,pitch e.t.c.

speak(): Speaks the text using the specified queuing strategy and speech parameters.

setLanguage(): Sets the text-to-speech language.

stop(): stop the speak.

shutdown(): releases the resources used by the TextToSpeech engine.

4. Now run your project and test your app by entering some text in input filed.

 

Changing Language

You can change language to speak by using setLanguage() method. Lot of languages are supported like Canada, French, Chinese, Germany etc.,

tts.setLanguage(Locale.CHINESE); // Chinese language
tts.setLanguage(Locale.FRENCH); // French language
tts.setLanguage(Locale.GERMAN); // German language

Changing Pitch Rate

You can set speech pitch for the TextToSpeech engine by using setPitch() function. By default the value is 1.0 You can set lower values than 1.0 to decrease pitch level or greater values for increase pitch level.

tts.setPitch(0.6f);

Changing Speech Rate

The speech rate can be set using setSpeechRate(). It also takes default of 1.0 value.

tts.setSpeechRate(2f);

1 thought on “Android Text to Speech Example”

  1. hey i basically want to make an app that extracts text and translates into desired language and then text to speech everything using ml kit can u compile everything into one code and send me code it will be great him

Leave a Reply