Android text to speech example

Welcome back readers!! Before I start with the post, would like to say thanks for your constant feedback and appreciations which I am getting in mails.

In this post, we are going to develop a simple application which reads out the text you typed. Sounds nice??. Follow the post to create one for you. :)

Package ‘android.speech.tts’:

Android SDK provides built-in package called ‘android.speech.tts’ to handle text to speech capabilities. It synthesizes speech from text for immediate playback or to create a sound file.

Let us start with the application development:

Quick Links

Project Structure

  • Create new android project [File >> New >> Android Project] with project name TexttoSpeech
  • Click next and select target android device version [I chose version 2.2]
  • Click next and enter package name – ‘com.prgguru.android’
  • Click finish

Code Listings

Layout creation:

Create a simple layout with one text box to get text from User and one button to trigger ‘Speak’ method to read out the text you typed.

Application layout – main.xml:

Open main.xml under /res/layout and add replace it with the below XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff"
    android:orientation="vertical"
    tools:ignore="HardcodedText" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="15dip"
        android:text="Text To Speech"
        android:textColor="#0587d9"
        android:textSize="26dip"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/txtText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dip"
        android:layout_marginTop="20dip"
        android:hint="Enter text to speak" />

    <Button
        android:id="@+id/btnSpeak"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dip"
        android:enabled="false"
        android:text="Speak" />

</LinearLayout>

Application layout will look like:

Change to graphical layout of main.xml, the layout design should look like below:

We are done with application layout. Now we will implement the logic in TextoSpeechActivity class, just open it and proceed with the below listings:

Implement onInitListener interface in your TexttoSpeechActivity class as shown below:

public class TexttoSpeechActivity extends Activity implements OnInitListener

Create following objects under TextoSpeechActivity class:

//create TextToSpeech native object
private TextToSpeech tts;
private Button btnSpeak;
private EditText txtText;

Update onCreate method with below snippet:

public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
                //Set application layout
		setContentView(R.layout.main);
                //Initialize the tts object
		tts = new TextToSpeech(this, this);
                //Refer 'Speak' button
		btnSpeak = (Button) findViewById(R.id.btnSpeak);
                //Refer 'Text' control
		txtText = (EditText) findViewById(R.id.txtText);
		//Handle onClick event for button 'Speak'
		btnSpeak.setOnClickListener(new View.OnClickListener() {

			public void onClick(View arg0) {
                                //Method yet to be defined 
 				speakOut();
			}

		});
	}

Include onInit method which signals the completion of the TextToSpeech engine initialization. Your device will take some small fraction of time to initialize TTS engine, so we are calling onInit method to make sure that whether it is initialized properly or not. Include the below code snipper following the onCreate method:

public void onInit(int status) {
		// TODO Auto-generated method stub
          //TTS is successfully initialized
		if (status == TextToSpeech.SUCCESS) {
                       //Setting speech language
			int result = tts.setLanguage(Locale.US);
		   //If your device doesn't support language you set above
			if (result == TextToSpeech.LANG_MISSING_DATA
					|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
                           //Cook simple toast message with message
				Toast.makeText(this, "Language not supported", Toast.LENGTH_LONG).show();
				Log.e("TTS", "Language is not supported");
			} 
                 //Enable the button - It was disabled in main.xml (Go back and Check it)
                        else {
				btnSpeak.setEnabled(true);
			}
            //TTS is not initialized properly
		} else {
                    Toast.makeText(this, "TTS Initilization Failed", Toast.LENGTH_LONG).show();
			Log.e("TTS", "Initilization Failed");
		}
	}

Create ‘Speak’ method which handles speech activity:

private void speakOut() {
         //Get the text typed
		String text = txtText.getText().toString();
         //If no text is typed, tts will read out 'You haven't typed text'
         //else it reads out the text you typed
		if (text.length() == 0) {
			tts.speak("You haven't typed text", TextToSpeech.QUEUE_FLUSH, null);
		} else {
			tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
		}

	}

TextToSpeech object – tts service should be shut down when the application is about to be closed, add onDestroy method:

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

[pglinkadssmall1]

Demo

Let us test the application:
Run click on the project >> Run as >> Android application >> Choose emulator or device
You could see this screen:

Try clicking ‘Speak’ button with and without providing text.

Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project(How to import android project in eclipse). If you just want to run the application in your mobile and see the output but don’t want to hit your head with source code, download application(apk) file and install it in your mobile device.

Download Source Code Download Application(apk)

*apk in Android is the installation file simliar to exe in windows.

[pglinkadssmall]

Reference:

Android Audio TextToSpeech

Package ‘android.speech.tts’/a>

I hope you enjoyed the post!! :)

Suggested posts for further reading


[pgfeedback]
[pgwriteforus]

Author: Android Guru

Share This Post On
  • Eshrath

    its working…. great..

  • ali r?za

    Hi. it is working succesfully on emulator but voice is not working on telephone. can you help me. Good working…

  • Er. Surya Prakash Chamoli

    this help m lot…thx sir

    • http://programmerguru.com/android-tutorial Android Guru

      Welcome Surya!

  • Raghu

    Hi Sir,
    I am using this code in my app. But it is giving an error in log file “Initialization Failed”.

    which means that i am not able to enter if condition of onInit() function and when i Toast status value it showing -1.

    how to solve this problem pls help me. ASAP

  • santosh

    sir plz how to male voice to and speech text

  • Kaviraj

    Hello Sir …. I have multiple text fields , could you please tell me how could i implement this? Thanks in advance.

    • http://programmerguru.com/android-tutorial Android Guru

      Have textbox and button pairs in the UI. Speak out the text present in the text box when the button associated with that textbox is clicked.

  • http://www.appzuniverse.com Appzuniverse

    Good article, Its really working well for all android devices?

  • http://programmerguru.com/android-tutorial/ Android Guru

    It works for the devices which has Android OS versions that suppor TTS package.

Join now to get more access to our Android Tutorials

Join now to get more access to our Android Tutorials

Once you Join, you will receive Mail containing latest Android Tutorials once a month !!

I promise I wont spam you !!

You have Successfully Subscribed!

Pin It on Pinterest

Shares