Saturday, October 23, 2010

Text To Speech Example In Android

I had the opportunity to incorporate Text To Speech feature in E-Book apps in Android at Salsoft Technologies for Feel Social.Here is a neat example how to use the android.speech.tts.TextToSpeech
library.

Take an Edit Text Box and  a Button and run the following code and feel free to leave your comments:


package az.tts;


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;
import android.widget.Toast;


public class TexttoSpeech extends Activity implements OnInitListener {
    /** Called when the activity is first created. */
private EditText text;
private TextToSpeech tts;
private String str="";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        tts = new TextToSpeech(this, this);
        text = (EditText) findViewById(R.id.EditText01);
        //text.setText("Press me");
        str = text.getText().toString();
      
        Button btn = (Button)findViewById(R.id.Button01);
        btn.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
str = text.getText().toString();
tts.speak(str, TextToSpeech.QUEUE_FLUSH, null );
    Toast.makeText(TexttoSpeech.this, text.getText().toString(), Toast.LENGTH_SHORT).show();
   

}
});
      
    
    }


@Override
public void onInit(int status) {
// TODO Auto-generated method stub
tts.speak(str, TextToSpeech.QUEUE_FLUSH, null );
Toast.makeText(TexttoSpeech.this, text.getText().toString(), Toast.LENGTH_SHORT).show();

}
}

No comments:

Post a Comment