Text To Speech in Android Example


          Android provides Speech package that makes Text to Speech conversion very easy. 
android.speech.tts.TextToSpeach class provides necessary methods to the trick. 
At the start we need to implement the TextToSpeech.OnInitListener to do the initialization. During initialization we can set the Locale, Audio pitch rate, audio speed.
setLanguage() method is used to set the language.
Example: setLanguage(Locale.US);

TextToSpeech.LANG_MISSING_DATA indicates that language data is missing.
TextToSpeech.LANG_NOT_SUPPORTED indicates that language is not supported.
We check all these conditions during initialization.

speak() method in the TextToSpeech class is used to convert text to speech. Here we can set different types of Queue modes. TextToSpeech.QUEUE_FLUSH will flush the playback queue by replacing the old entries with new entry. TextToSpech.QUEUQ_ADD will add the new entry at the end of the playback queue.

It is a good practice to release the resources used by the TextToSpeech engine by calling shutdown() method. Normally we do call shutdown() method inside onDestroy() of the activity.

In the example application I have created a Text field to get the input text from user and a control button to initiate the Text To Speech conversion.

Layout file:
tts_layout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".TextToSpeechActivity" >

    <EditText
        android:id="@+id/inputText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="42dp"
        android:layout_marginTop="28dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/inputText"
        android:layout_below="@+id/inputText"
        android:layout_marginTop="14dp"
        android:text="Speak" />

</RelativeLayout>

Activity class:
TextToSpeechActivity.java

package com.example.texttospeech;

import java.util.Locale;

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

/**
 * Reads the input value from the user and converts into voice.
 * 
 * @author Prabu
 * @since Aug 09 2013
 * @version 1.0
 * 
 */
public class TextToSpeechActivity extends Activity implements
  TextToSpeech.OnInitListener {
 private TextToSpeech textToSpeech;
 private Button button;
 private EditText inputText;

 /**
  * @see android.app.Activity#onCreate(android.os.Bundle)
  */
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.tts_layout);
  button = (Button) findViewById(R.id.button1);
  inputText = (EditText) findViewById(R.id.inputText);
  textToSpeech = new TextToSpeech(this, this);
  button.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View arg0) {
    convertTextToSpeech();
   }

  });
  convertTextToSpeech();
 }

 /**
  * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
  */
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.tts_layout, menu);
  return true;
 }

 /**
  * a callback to be invoked indicating the completion of the TextToSpeech
  * engine initialization.
  * 
  * @see android.speech.tts.TextToSpeech.OnInitListener#onInit(int)
  */
 @Override
 public void onInit(int status) {
  if (status == TextToSpeech.SUCCESS) {
   int result = textToSpeech.setLanguage(Locale.US);
   if (result == TextToSpeech.LANG_MISSING_DATA
     || result == TextToSpeech.LANG_NOT_SUPPORTED) {
    Log.e("error", "This Language is not supported");
   } else {
    convertTextToSpeech();
   }
  } else {
   Log.e("error", "Initilization Failed!");
  }
 }

 /**
  * Releases the resources used by the TextToSpeech engine. It is good
  * practice for instance to call this method in the onDestroy() method of an
  * Activity so the TextToSpeech engine can be cleanly stopped.
  * 
  * @see android.app.Activity#onDestroy()
  */
 @Override
 public void onDestroy() {
  textToSpeech.shutdown();
 }

 /**
  * Speaks the string using the specified queuing strategy and speech
  * parameters.
  */
 private void convertTextToSpeech() {
  String text = inputText.getText().toString();
  if (null == text || "".equals(text)) {
   text = "Please give some input.";
  }
  textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
 }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.texttospeech"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.texttospeech.TextToSpeechActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Output screenshot:

output screenshot

Thats it!! We are done with Text To Speech Android Example. Don't forget to share your thought!!

Source code of this application:
TextToSpeech.zip

 



Reactions:

1 comment :