This code snippet described the
Text-to-Speech (TTS) capability. Also known as "speech
synthesis" for Android Devices. TTS enables Android device to
"speak" text of different languages. Mostly all
Android-powered devices that are supporting the TTS functionality
comes with the TTS engine integrated. But some devices lacks it.
There is an API available which checks the TTS engine and install it
on device if it is not there.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class TextToSpeechActivity extends Activity implements OnInitListener {
private int CURRENT_DATA_CHECK_CODE = 0;
// Instance of TextToSpeech
private TextToSpeech oTTS;
// Object for the Editable Text Input
private EditText inputTextControl;
// Object for the button
private Button speakButtonControl;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
inputTextControl = (EditText) findViewById(R.id.input_text);
speakButtonControl = (Button) findViewById(R.id.speak_button);
speakButtonControl.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String strText = inputTextControl.getText().toString();
if (strText!=null && strText.length()>0) {
Toast.makeText(TtsActivity.this, "Testing: " + strText, Toast.LENGTH_LONG).show();
oTTS.speak(strText, TextToSpeech.QUEUE_ADD, null);
}
}
});
Intent checkIntent = new Intent();
newIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
// startActivityForResult will wait till the current intent will not be interpreted
startActivityForResult(newIntent, CURRENT_DATA_CHECK_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CURRENT_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// on successful call create the TTS instance
oTTS = new TextToSpeech(this, this);
}
else {
// data may be missing so install it
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Toast.makeText(TtsActivity.this,
"Text-To-Speech engine has been initialized", Toast.LENGTH_LONG).show();
}
else if (status == TextToSpeech.ERROR) {
Toast.makeText(TtsActivity.this,
"Error occurred initializing Text-To-Speech engine", Toast.LENGTH_LONG).show();
}
}
}

