Skip to main content

Android Text To Speech

Android sdk is coming with a very simple to use method to speak out your text in Many languages. We can simply access the method without importing any library or any other external sdk.

Step 1: Implement TextToSpeech to your Activity

You will have to implement the TextToSpeechOnInitListener this will tell you the status of the Text to Speech client.

public class MainActivity extends AppCompatActivity implements
        TextToSpeech.OnInitListener  {

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

 

Step 2: Initialize the Text To Speech Listener

You can initialize the text to speech by overriding the function OnInit() and it will return TextToSpeech.SUCCESS

if the initialization is successful.

Using the Following code snippet you can change to the desired languages by changing Locale.US to your desired languages

@Override
public void onInit(int status) {
    if (status == TextToSpeech.SUCCESS) {

        int result = tts.setLanguage(Locale.US);// You can set the Language here

        if (result == TextToSpeech.LANG_MISSING_DATA
                || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            Log.e("TTS", "This Language is not supported");
        } else {
             // Means the initialization is successfull and im changing the boolean initialized to true
            initialized=true;
            speakOut();
        }

    } else {
        Log.e("TTS", "Initilization Failed!");
    }


}

 

Step 3 : SpeakOut()

This function will speakout the text

private void speakOut() {

    String text = "Here is the Text To Speak";

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

# Final MainActivity.java

Here is my final Main activity which takes input from user edittext and speak out by a buttin press.

package info.androidcodes.androidtexttospeech;

import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;

import java.util.Locale;

public class MainActivity extends AppCompatActivity implements
        TextToSpeech.OnInitListener  {
    TextToSpeech tts;
    EditText editText;
    boolean initialized;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        initialized=false;

        tts = new TextToSpeech(this, this);


        editText = (EditText) findViewById(R.id.editText);


        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(initialized) {
                    speakOut();
                    Snackbar.make(view, "Speech Starteds", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();
                }else Snackbar.make(view, "Initialization Failed", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @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 {
                // Means the initialization is successfull and im changing the boolean initialized to true
                initialized=true;
                speakOut();
            }

        } else {
            Log.e("TTS", "Initilization Failed!");
        }


    }
    @Override
    public void onDestroy(){
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
    }
    private void speakOut() {

        String text = editText.getText().toString();

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

 

#  Final activity_main.xml

Here is the UI part which i used for making user input. this include an edittext and a button

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
    android:fitsSystemWindows="true"
    tools:context="ifo.androidcodes.androidtexttospeech.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

 

# Final content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="ifo.androidcodes.androidtexttospeech.MainActivity"
    tools:showIn="@layout/activity_main">

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:id="@+id/editText" />
</RelativeLayout>

 

# Result