Industrial Training




Android - Text to Speech


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 initListener. 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 available are given below −

Sr.No Locale
1

US

2

CANADA_FRENCH

3

GERMANY

4

ITALY

5

JAPAN

6

CHINA

Once you have set the language, you can call speakmethod 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 available in the TextToSpeech class. They are listed below −

Sr.No Method & description
1

addSpeech(String text, String filename)
This method adds a mapping between a string of text and a sound file.

2

getLanguage()
This method returns a Locale instance describing the language.

3

isSpeaking()
This method checks whether the TextToSpeech engine is busy speaking.

4

setPitch(float pitch)
This method sets the speech pitch for the TextToSpeech engine.

5

setSpeechRate(float speechRate)
This method sets the speech rate.

6

shutdown()
This method releases the resources used by the TextToSpeech engine.

7

stop()
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.

Steps Description
1

You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication.

2

Modify src/MainActivity.java file to add TextToSpeech code.

3

Modify layout XML file res/layout/activity_main.xml add any GUI component if required.

4

Run the application and choose a running android device and install the application on it and verify the results.

Here is the content of src/MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;
import android.widget.Toast;

public class MainActivity extends Activity {
   TextToSpeech t1;
   EditText ed1;
   Button b1;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      ed1=(EditText)findViewById(R.id.editText);
      b1=(Button)findViewById(R.id.button);

      t1=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
         @Override
         public void onInit(int status) {
            if(status != TextToSpeech.ERROR) {
               t1.setLanguage(Locale.UK);
            }
         }
      });

      b1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            String toSpeak = ed1.getText().toString();
            Toast.makeText(getApplicationContext(), toSpeak,Toast.LENGTH_SHORT).show();
            t1.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
         }
      });
   }

   public void onPause(){
      if(t1 !=null){
         t1.stop();
         t1.shutdown();
      }
      super.onPause();
   }
}

Here is the content of activity_main.xml

< ?xml version="1.0" encoding="utf-8"?>
< 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:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin"
   tools:context=".MainActivity"
   android:transitionGroup="true">
   
   < TextView android:text="Text to Speech" android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/textview"
      android:textSize="35dp"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true" />
      
   < TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Mca tutorials"
      android:id="@+id/textView"
      android:layout_below="@+id/textview"
      android:layout_centerHorizontal="true"
      android:textColor="#ff7aff24"
      android:textSize="35dp" />
      
   < ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:src="@drawable/abc"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true"
      android:theme="@style/Base.TextAppearance.AppCompat" />
      
   < EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText"
      android:layout_below="@+id/imageView"
      android:layout_marginTop="46dp"
      android:hint="Enter Text"
      android:layout_alignParentRight="true"
      android:layout_alignParentEnd="true"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true"
      android:textColor="#ff7aff10"
      android:textColorHint="#ffff23d1" />
      
   < Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Text to Speech"
      android:id="@+id/button"
      android:layout_below="@+id/editText"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="46dp" />

< /RelativeLayout>

Here is the content of Strings.xml.

< resources>
   < string name="app_name">My Application< /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.sairamkrishna.myapplication" >
   < application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
   
      < activity
         android:name=".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 application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project's activity files and click Run eclipse_run icon from the toolbar. Before starting your application, android studio will display following window to select an option where you want to run your Android application.


choose_device

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

texttospeech

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 −

texttospeech1

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

texttospeech2



Hi I am Pluto.