Android - Text To Speech Tutorial

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 theinitListnere. 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 callingsetLanguage() 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.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 available 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 Android studio to create an Android application under a package com.example.sairamkrishna.myapplication. 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.
4Run 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.hardware.SensorManager;
import android.os.Bundle;

import android.speech.tts.TextToSpeech;
import android.util.Log;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.util.List;
import java.util.Locale;

import android.hardware.Sensor;
import android.hardware.SensorManager;
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();
   }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.menu_main, menu);
      return true;
   }
   
   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      
      int id = item.getItemId();
      
      //noinspection SimplifiableIfStatement
      if (id == R.id.action_settings) {
         return true;
      }
      return super.onOptionsItemSelected(item);
   }
}
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: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="Tutorials point"
      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>
   <string name="hello_world">Hello world!</string>
   <string name="action_settings">Settings</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 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.
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

Comments

Popular posts from this blog

Android - TextureView Tutorial

Android - JetPlayer Tutorial

Android - Notifications