Android Text To Speech Tutorial

Android Text To Speech Tutorial

In this android tutorial we are going to learn how to create android text to speech application. Android has a text to speech engine that can convert words to speech.

This can come in handy in different android applications like a dictionary application where users can use the speech feature to understand the real pronunciation of a particular word.

I have develop a full functional dictionary application with TextToSpeech feature. I will suggest you read the post before you continue with this post – Android Dictionary Application with Text to Speech Feature.

A TextToSpeech instance can only be used to synthesize text once it has completed its initialization. Implement the TextToSpeech.OnInitListener to be notified of the completion of the initialization. When you are done using the TextToSpeech instance, call the shutdown() method to release the native resources used by the TextToSpeech engine.

We are going to use an EditText View to get input from users and the input will be converted to speech. The button View event listener callback method will contain an instance of a TextToSpeech object which implements onInitListener interface.

The TextToSpeech object will then call its speak method which has the EditText input string as one of its parameters.

You can use the setLanguage() method to set the language of the TextToSpeech engine object. There are many other methods that can be use to enhance the speech feature. You can find more about these methods and properties in the android developers guide

Before we start, the first thing I will do is to list the environment and tools I used in this android tutorial but feel free to use whatever environment or tools you are familiar with.

Windows 7

Android Studio

Samsung Galaxy Fame Lite

Min SDK 14

Target SDK 19

To create a new android application project, following the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidTextToSpeech

Package: com.inducesmile.androidtexttospeech

Keep other default selections.

Continue to click on next button until Finish button is active, then click on Finish Button

Once you are done with creating your project, make sure you change the package name if you did not use the same package.

activity_main.xml

We are going to add a Button and EditView controls in our main layout. If you are using Eclipse IDE or Android Studio, you can use the design view to drag and drop these components in the layout file.

The following is the code for the layout file.

<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">

<EditText

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:id="@+id/speech_input"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true"

android:layout_marginTop="27dp" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/text_to_speech"

android:id="@+id/text_to_speech"

android:layout_below="@+id/speech_input"

android:layout_centerHorizontal="true"

android:layout_marginTop="36dp" />

</RelativeLayout>

 MainActivity.java

We will finish up the project by writing the code that will let a user to enter an input and click on the button view to convert to text to speech.

We will get the instances of our layout view controls by calling the findViewById method of the Activity class.

We will further have to create an instance of the TextToSpeed class which implements onInit callback method that signify when the TextToSpeech engine is ready to be used.

The TextToSpeech object is instantiated inside the button’s event listener and the speak method is called on the object.

The code for the class is shown below.

package inducesmile.com.androidtexttospeech;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.Locale;

public class MainActivity extends ActionBarActivity {

    private EditText userInputToSpeech;
    private TextToSpeech convertToSpeech;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        userInputToSpeech = (EditText)findViewById(R.id.speech_input);
        Button textToSpeech = (Button)findViewById(R.id.text_to_speech);

        textToSpeech.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String convertTextToSpeech = userInputToSpeech.getText().toString();
                if (convertTextToSpeech.equals("")) {
                    Toast.makeText(MainActivity.this, "The input field must not be empty", Toast.LENGTH_LONG).show();
                    return;
                }
                convertToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
                    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                    @Override
                    public void onInit(int status) {
                        if (status != TextToSpeech.ERROR) {
                            convertToSpeech.setLanguage(Locale.US);
                            convertToSpeech.speak(convertTextToSpeech, TextToSpeech.QUEUE_FLUSH, null, null);
                        }
                    }
                });
            }
        });
    }
    @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);
    }
}

Save the file and run your project. If everything works for you, the project will appear like this in your device.

Android Text To Speech

You can download the code for this tutorial below. If you are having hard time downloading the tutorials, kindly contact me.

Remember to subscribe with your email so that you will be among the first to receive our new post once it is published

OTHER INTERESTING POSTS:

Add a Comment