Ilias Tsagklis

About Ilias Tsagklis

Ilias Tsagklis is a senior software engineer working in the telecom domain. He is an applications developer in a wide variety of applications/services. Ilias is co-founder and Executive Editor at Java Code Geeks.

Android Text-To-Speech Application

One of the many features that Android provides out of the box is the one of “speech synthesis”. This is also known as “Text-To-Speech” (TTS) and is mainly the capability of the device to “speak” text of different languages. This feature was introduced in version 1.6 of the Android platform and you can find an introductory article at the official Android-Developers blog.

In this tutorial I am going to show you how to quickly introduce TTS capabilities into your application.

Let’s get started by creating a new Eclipse project under the name “AndroidTextToSpeechProject” as shown in the following image:

Note that Android 1.6 was used as the build target and that for the minimum SDK version I used the value 4, since this functionality is not provided by the previous versions.

The first step to use the TTS API is to check if it is actually supported by the device. For that purpose there is a special action named ACTION_CHECK_TTS_DATA which is included in the TextToSpeech.Engine. As the Javadoc states, this is used by an Intent to “verify the proper installation and availability of the resource files on the system”. In case the resourses are not available, another action named ACTION_INSTALL_TTS_DATA is used in order to trigger their installation. Note that the SDK’s emulator supports TTS with no configuration needed.

Before using the TTS engine, we have to be sure that it has properly been initialized. In order to get informed on whether this has happened, we can implement an interface called OnInitListener. The method onInit will be invoked when the engine initialization has completed with the accompanying status.

After initialization, we can use the TextToSpeech class to make the device speak. The relevant method is named speak, where the text, the queue mode and some additional parameters can be passed. It is important to describe queue mode. It is the queuing strategy to be used by the TTS engine, i.e. what to do when a new text has been queued to the engine. There are two options:

  • QUEUE_ADD: the new entry is added at the end of the playback queue
  • QUEUE_FLUSH: all entries in the playback queue (media to be played and text to be synthesized) are dropped and replaced by the new entry

All the above are translated to the code provided below:

package com.javacodegeeks.android.tts;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class TtsActivity extends Activity implements OnInitListener {
    
    private int MY_DATA_CHECK_CODE = 0;
    
    private TextToSpeech tts;
    
    private EditText inputText;
    private Button speakButton;
    
 @Override
 public void onCreate(Bundle savedInstanceState) {
    
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  
  inputText = (EditText) findViewById(R.id.input_text);
  speakButton = (Button) findViewById(R.id.speak_button);
  
  speakButton.setOnClickListener(new OnClickListener() {            
   @Override
   public void onClick(View v) {
       String text = inputText.getText().toString();
       if (text!=null && text.length()>0) {
    Toast.makeText(TtsActivity.this, "Saying: " + text, Toast.LENGTH_LONG).show();
    tts.speak(text, TextToSpeech.QUEUE_ADD, null);
       }
   }
      });
  
  Intent checkIntent = new Intent();
      checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
      startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
        
    }
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == MY_DATA_CHECK_CODE) {
            if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
                // success, create the TTS instance
                tts = new TextToSpeech(this, this);
            } 
            else {
                // missing data, install it
                Intent installIntent = new Intent();
                installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(installIntent);
            }
        }

    }

    @Override
    public void onInit(int status) {        
        if (status == TextToSpeech.SUCCESS) {
            Toast.makeText(TtsActivity.this, 
                    "Text-To-Speech engine is initialized", Toast.LENGTH_LONG).show();
        }
        else if (status == TextToSpeech.ERROR) {
            Toast.makeText(TtsActivity.this, 
                    "Error occurred while initializing Text-To-Speech engine", Toast.LENGTH_LONG).show();
        }
    }
    
}

The engine support is checked in the onActivityResult method. If there is support for TTS, we initialize the engine, else a new Intent is launched in order to trigger the relevant installation. After initialization, we used a Toast in order to notify the user about the operation status. Finally, we use a text field where the text is provided by the user and a button which feeds the engine with the provided text.

In order to run the project, an appropriate emulator device is needed. If you have none available, use the following configuration in the AVD manager (note that “Android 1.6 – API Level 4” or higher is needed):

Provide the text you wish to hear into the text field, hit the button and listen to emulator speak to you!

That’s all folks, nice and simple. Now, make your devices speak! You can download the created Eclipse project here.

Related Articles :
Related Whitepaper:

Rapid Android Development: Build Rich, Sensor-Based Applications with Processing

Create mobile apps for Android phones and tablets faster and more easily than you ever imagined

Use 'Processing', the free, award-winning, graphics-savvy language and development environment, to work with the touchscreens, hardware sensors, cameras, network transceivers, and other devices and software in the latest Android phones and tablets.

Get it Now!  

13 Responses to "Android Text-To-Speech Application"

  1. manuw says:

    I wrote a Text-To-Speech app just for fun.
    Source: https://github.com/manuw/MyVoice

  2. Yash Raithatha says:

    alert(‘Filter user input. They can insert anything’);

  3. kuldeep singh says:

    i want to create an app which reads email. is it possible if yes then how? pls send me appropriate codes.
    my email id is: kskuldeep230@gmail.com

  4. Selvameena N says:

    Hi Deepthy,

    i used ur code and working fine but i included a back button and calling finish(); .This forcing my app to stop unexpectedly. why is this so? help me

  5. santosh says:

    sir how to set male voice to text to speech

  6. santosh says:

    plz snd reply to my mail id

  7. niyas says:

    its is possible to leave a time gap between two words pronounciation in text to speech………..after a words pronounced only next word should come

  8. saranya says:

    i need an abstract documentation for this text to speech conversion will u plz provide it for me, and when i m running the emulator its not responding and sometimes it failed to install …. how can i run it ?give me solution

  9. Priyanka says:

    sir its nt workng…do we have to take any permission in the mainfest file…????

  10. Ravi Agarwal says:

    Its awesome

  11. Dineesh says:

    i required the android code for voice visualizer from microphone.if got please send to my email id:dineesh2503@gmail.com

  12. Aouie says:

    hello peeps … Im a newbie in programming …but since the source code here is ready to copy and paste …i thought it will work just fine … but i was just frustrated … can anyone please help me how to do this step by step … here is what I did : 1. i opened my eclipse … 2.then i followed how to make the emulator … 3.then i created a new eclipse project with the suggested filename .. 4. then i pasted the source code in between the relative layout .. 5. i clicked run … and nothing happened. what am i doing wrong? thanks guys …

Leave a Reply


+ 7 = fourteen



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books