Android Text To Speech Tutorial

Advertisements


Android allows you convert your text into voice. Not only you can convert it but it also allows you to speak text in variety of different languages.

Android provides TextToSpeech class for this purpose. In order to use this class, you need to instantiate an object of this class and also specify the initListnere. Its syntax is given below:

private EditText write;
ttobj=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
   @Override
   public void onInit(int status) {
   }
}
);

In this listener , you have to specify the properties for TextToSpeech object , such as its language ,pitch e.t.c. Language can be set by calling setLanguage() method. Its syntax is given below:

ttobj.setLanguage(Locale.UK);

The method setLanguage takes an Locale object as parameter. The list of some of the locales availaible are given below:

Sr.NoLocale
1US
2CANADA_FRENCH
3GERMANY
4ITALY
5JAPAN
6CHINA

Once you have set the language, you can call speak method of the class to speak the text. Its syntax is given below:

ttobj.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);

Apart from the speak method, there are some other methods availaible in the TextToSpeech class. They are listed below:

Sr.NoMethod & description
1addSpeech(String text, String filename)
This method adds a mapping between a string of text and a sound file.
2getLanguage()
This method returns a Locale instance describing the language.
3isSpeaking()
This method checks whether the TextToSpeech engine is busy speaking.
4setPitch(float pitch)
This method sets the speech pitch for the TextToSpeech engine.
5setSpeechRate(float speechRate)
This method sets the speech rate.
6shutdown()
This method releases the resources used by the TextToSpeech engine.
7stop()
This method stop the speak.

Example

The below example demonstrates the use of TextToSpeech class. It crates a basic application that allows you to set write text and speak it.

To experiment with this example , you need to run this on an actual device.

StepsDescription
1You will use Eclipse IDE to create an Android application and name it as TextToSpeech under a package com.example.texttospeech. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file to add TextToSpeech code.
3Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
4Modify res/values/string.xml file and add necessary string components.
5Run the application and choose a running android device and install the application on it and verify the results.

Here is the content of src/com.example.texttospeech/MainActivity.java.

package com.example.texttospeech;

import java.util.Locale;
import java.util.Random;

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

public class MainActivity extends Activity {

   TextToSpeech ttobj;
   private EditText write;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      write = (EditText)findViewById(R.id.editText1);
      ttobj=new TextToSpeech(getApplicationContext(), 
      new TextToSpeech.OnInitListener() {
      @Override
      public void onInit(int status) {
         if(status != TextToSpeech.ERROR){
             ttobj.setLanguage(Locale.UK);
            }				
         }
      });
   }
   @Override
   public void onPause(){
      if(ttobj !=null){
         ttobj.stop();
         ttobj.shutdown();
      }
      super.onPause();
   }
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   }
   public void speakText(View view){
      String toSpeak = write.getText().toString();
      Toast.makeText(getApplicationContext(), toSpeak, 
      Toast.LENGTH_SHORT).show();
      ttobj.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);

   }
}

Here is the content of activity_main.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"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".MainActivity" >

   <Button
      android:id="@+id/button1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentBottom="true"
      android:layout_alignParentRight="true"
      android:layout_marginBottom="188dp"
      android:layout_marginRight="67dp"
      android:onClick="speakText"
      android:text="@string/text1" />

   <EditText
      android:id="@+id/editText1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_above="@+id/button1"
      android:layout_centerHorizontal="true"
      android:layout_marginBottom="81dp"
      android:ems="10" >
      <requestFocus />
   </EditText>

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="20dp"
      android:text="@string/write"
      android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>

Here is the content of Strings.xml.

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="app_name">TextToSpeech</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">Hello world!</string>
   <string name="text1">Text to Speech</string>
   <string name="write">Write Text</string>
</resources>

Here is the content of 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="17" />

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      <activity
         android:name="com.example.texttospeech.MainActivity"
         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>

Let's try to run your TextToSpeech application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Eclipse, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Before starting your application, Eclipse will display following window to select an option where you want to run your Android application.

Anroid Text To Speech Tutorial

Select your mobile device as an option and then check your mobile device which will display following screen.

Android Text To Speech  Tutorial

Now just type some text in the field and click on the text to speech button below. A notification would appear and text will be spoken. It is shown in the image below:

Android Text To Speech  Tutorial

Now type something else and repeat the step again with different locale. You will again hear sound. This is shown below:

Android Text To Speech  Tutorial

Advertisements
Advertisements