May 10, 2011

Implement Android's Text to speech function

Android's Text to speech function

package com.AndroidTTS;

import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class AndroidTTS extends Activity implements OnInitListener{

TextToSpeech tts;
EditText textIn;
Button buttonSpeech;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

tts = new TextToSpeech(this, this);

textIn = (EditText)findViewById(R.id.textin);
buttonSpeech = (Button)findViewById(R.id.speech);

buttonSpeech.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String textToBeSpeech = textIn.getText().toString();
tts.speak(textToBeSpeech, TextToSpeech.QUEUE_ADD, null);
}});
}

@Override
public void onInit(int arg0) {
// TODO Auto-generated method stub
//Make sure the Text-To-Speech engine is fully loaded
//It can be configured and used
buttonSpeech.setEnabled(true);
}

@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
tts.shutdown();
}
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<EditText
android:id="@+id/textin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/speech"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Speech"
android:enabled="false"
/>
</LinearLayout>


3 comments:

  1. This is not a full implementation since it does not handle missing lang data and languages at all. Please refer to Google docs or better implementations.

    This may be ok for a quick play around, but for serious app development ..ignore.

    ReplyDelete

Infolinks In Text Ads