Android Tutorial – Text to Speech

Here is the sample code along with the .apk file for android text to speech conversion.

Android Text to speech picture

MainActivity.java File

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 AndroidTextToSpeechActivity extends Activity implements
TextToSpeech.OnInitListener {
/** Called when the activity is first created. */

private TextToSpeech tts;
private Button btnSpeak;
private EditText txtText;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

tts = new TextToSpeech(this, this);

btnSpeak = (Button) findViewById(R.id.btnSpeak);

txtText = (EditText) findViewById(R.id.txtText);

// button on click event
btnSpeak.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”, “This Language is not supported”);
} else {
btnSpeak.setEnabled(true);
speakOut();
}

} else {
Log.e(“TTS”, “Initilization Failed!”);
}

}

private void speakOut() {

String text = txtText.getText().toString();

tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}

}

main_activity.xml File

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”vertical” >

<TextView
android:id=”@+id/textView”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:layout_gravity=”center”
android:gravity=”center”
android:text=”Text To Speech” />

<EditText
android:id=”@+id/editText”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content” />

<Button
android:id=”@+id/btnSpeak”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Speak” />

</LinearLayout>

Here is the requied Files of Text To Speech:

Text to speech files

Leave a comment