TextToSpeech is the great feature of Android. Text to Speech (TTS) which speaks the text in different languages usually selected by the user or you can also put the default user language for the TTS.
First of all make the xml file with the one EditText and Button. And make the following code working in your java file for the TTS. You need to implement the Interface of the TTS TextToSpeech.OnInitListener.
First of all make the xml file with the one EditText and Button. And make the following code working in your java file for the TTS. You need to implement the Interface of the TTS TextToSpeech.OnInitListener.
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) {
TTS();
}
});
}
@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);
TTS();
}
}
btnSpeak.setEnabled(true);
TTS();
}
}
else
{
Log.e("TTS", "Initilization Failed!");
}
}
private void TTS() {
String text = txtText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
You can change the language by the oneline code
Log.e("TTS", "Initilization Failed!");
}
}
private void TTS() {
String text = txtText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
You can change the language by the oneline code
tts.setLanguage(Locale.GERMANY);
tts.setSpeechRate(1.5);
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.