TextToSpeech Android

The TextToSpeech class in Android is used to convert a text into speech. We can also playback the speech and can create a sound file, once the text is converted to speech.

The constructor of the TextToSpeech class:

TextToSpeech(Context context, TextToSpeech.OnInitListener)

Methods of TextToSpeech class:

The Android TextToSpeech class contains various methods. The popular methods of the TextToSpeech class are described below. These are:

Method Uses
int speak (String text, int queueMode, HashMap params) Used to convert the text into speech. Queue Mode: QUEUE_ADD or QUEUE_FLUSH. Request parameters: null, KEY_PARAM_STREAM, KEY_PARAM_VALUME etc.
int setSpeechRate(float speed) Used to set the speed for the speech.
int setPitch(float speed) Used to set the pitch for the speech.
int setLanguage (Locale loc) Used to set the locale specific language for the speech.
void shutdown() Used to release the resource set by TextToSpeech Engine.
int stop() Used to interrupt the current utterance, whether it is played or rendered to file and to discard the other utterances in the queue.

TextToSpeech.OnInitListener Interface:

To perform event handling on the TextToSpeech engine, the TextToSpeech.OnInitListener interface needs to be implemented.

Method of TextToSpeech.OnInitListener Interface:

TextToSpeech.OnInitListener interface contains only one method. It is described below.

Method Uses
void onInit (int status) Used to signal the completion of the TextToSpeech engine initialization. Value of the status parameter: SUCCESS or ERROR.

Android TextToSpeech Example 1:

In the below example, we are demonstrating the usage of the Android TextToSpeech class to convert a text into speech.

activity_main.xml:

In the activity_main.xml file, we will drag a TextView, an EditText, and a button from the palette.

<!--?xml version="1.0" encoding="utf-8"?-->
 
 
 
 
 
 
 
    <button>
 
 
 
</button>

Activity class:(File: MainActivity.java)

In the MainActivity. java file, we will write the code to speak the written text.

package com.example.radioapp;
 
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.util.Locale;
 
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements
        TextToSpeech.OnInitListener {
    /** Called when the activity is first created. */
 
    private TextToSpeech tts;
    private Button buttonSpeak;
    private EditText editText;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        tts = new TextToSpeech(this, this);
        buttonSpeak = (Button) findViewById(R.id.button1);
        editText = (EditText) findViewById(R.id.editText1);
 
        buttonSpeak.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                speakOut();
            }
 
        });
    }
 
    @Override
    public void onDestroy() {
// Don't forget to shutdown tts!
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
        super.onDestroy();
    }
 
    @Override
    public void onInit(int status) {
 
        if (status == TextToSpeech.SUCCESS) {
 
            int result = tts.setLanguage(Locale.US);
 
            if (result == TextToSpeech.LANG_MISSING_DATA
                    || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                Log.e("TTS", "Language not supported");
            } else {
                buttonSpeak.setEnabled(true);
                speakOut();
            }
 
        } else {
            Log.e("TTS", "Failed!");
        }
 
    }
 
    private void speakOut() {
        String text = editText.getText().toString();
        tts.speak(text, TextToSpeech.QUEUE_FLUSH, 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, menu);
        return true;
    }
 
}

Output 1:

Output 2:

Android TextToSpeech Example 2:

In the below example, we are demonstrating the usage of the Android TextToSpeech class to convert a text into speech with speed and pitch options.

activity_main.xml:

In the activity_main.xml file, we will drag two TextView, an EditText, a Spinner, and a button from the palette.

<?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"
    tools:context=".MainActivity" >
 
    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView1"
        android:layout_alignBottom="@+id/textView1"
        android:layout_alignParentRight="true"
        android:layout_marginRight="58dp"
        android:ems="10" >
 
        <requestFocus />
    </EditText>
 
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="28dp"
        android:text="Speak" />
 
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_alignParentTop="true"
        android:layout_marginTop="42dp"
        android:text="Text Please:" />
 
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_marginTop="62dp"
        android:layout_toLeftOf="@+id/editText1"
        android:text="Select Speed:" />
 
    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView2"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="43dp" />
 
</RelativeLayout>

Activity class:(File: MainActivity.java)

In the MainActivity. java file, we will write the code to speak the written text. Here, we are also writing the code to set the different speech rates to select from.

package com.example.radioapp;
 
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
 
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends Activity implements
        TextToSpeech.OnInitListener,OnItemSelectedListener {
    /** Called when the activity is first created. */
 
    private TextToSpeech tts;
    private Button buttonSpeak;
    private EditText editText;
    private Spinner speedSpinner,pitchSpinner;
 
    private static String speed="Normal";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        tts = new TextToSpeech(this, this);
        buttonSpeak = (Button) findViewById(R.id.button1);
        editText = (EditText) findViewById(R.id.editText1);
        speedSpinner = (Spinner) findViewById(R.id.spinner1);
 
//load data in spinner
        loadSpinnerData();
        speedSpinner.setOnItemSelectedListener(this);
 
//button click event
        buttonSpeak.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                setSpeed();
                speakOut();
            }
 
        });
    }
 
 
    @Override
    public void onInit(int status) {
 
        if (status == TextToSpeech.SUCCESS) {
 
            int result = tts.setLanguage(Locale.US);
 
            if (result == TextToSpeech.LANG_MISSING_DATA
                    || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                Log.e("TTS", "This Language is not supported");
            } else {
                buttonSpeak.setEnabled(true);
                speakOut();
            }
 
        } else { Log.e("TTS", "Initialization Failed!");}
 
    }
 
    @Override
    public void onDestroy() {
// Don't forget to shutdown tts!
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
        super.onDestroy();
    }
 
    private void setSpeed(){
        if(speed.equals("Very Slow Speed")){
            tts.setSpeechRate(0.1f);
        }
        if(speed.equals("Slow Speed")){
            tts.setSpeechRate(0.5f);
        }
        if(speed.equals("Normal Speed")){
            tts.setSpeechRate(1.0f);//default 1.0
        }
        if(speed.equals("Fast Speed")){
            tts.setSpeechRate(1.5f);
        }
        if(speed.equals("Very Fast Speed")){
            tts.setSpeechRate(2.0f);
        }
        //for setting pitch you may call
        //tts.setPitch(1.0f);//default 1.0
    }
 
    private void speakOut() {
        String text = editText.getText().toString();
        tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
    }
 
    private void loadSpinnerData() {
        //Data for speed Spinner
        List<String> lables = new ArrayList<String>();
        lables.add("Very Slow Speed");
        lables.add("Slow Speed");
        lables.add("Normal Speed");
        lables.add("Fast Speed");
        lables.add("Very Fast Speed");
 
        // Creating adapter for spinner
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, lables);
 
        // Drop down layout style - list view with radio button
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
 
        // attaching data adapter to spinner
        speedSpinner.setAdapter(dataAdapter);
 
    }
 
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position,
                               long id) {
        // On selecting a spinner item
        speed = parent.getItemAtPosition(position).toString();
 
        Toast.makeText(parent.getContext(), "You selected: " + speed,
                Toast.LENGTH_LONG).show();
    }
 
    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
 
    }
 
 
    @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, menu);
        return true;
    }
 
}

Output 1:

Output 2: