Now possible to hear the spoken of words by Android.
Screenshot:
Code:
TextToSpeechActivity.java
text_to_speech.xml
Screenshot:
Code:
TextToSpeechActivity.java
package com.android.texttospeach;
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;
import java.util.Locale;
public class TextToSpeechActivity extends Activity implements
TextToSpeech.OnInitListener {
private static final String TAG = "MyTextToSpeechDemo";
private TextToSpeech mTts;
private Button mPlayButton;
EditText mEditText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text_to_speech);
// Initialize text-to-speech. This is an asynchronous operation.
mTts = new TextToSpeech(this, this);
mPlayButton = (Button) findViewById(R.id.button1);
mEditText = (EditText) findViewById(R.id.editText1);
mPlayButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
play();
}
});
}
@Override
public void onDestroy() {
// Don't forget to shutdown!
if (mTts != null) {
mTts.stop();
mTts.shutdown();
}
super.onDestroy();
}
// Implements TextToSpeech.OnInitListener.
public void onInit(int status) {
// status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR.
if (status == TextToSpeech.SUCCESS) {
int result = mTts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e(TAG, "Language is not available.");
} else {
mPlayButton.setEnabled(true);
play();
}
} else {
Log.e(TAG, "Could not initialize TextToSpeech.");
}
}
private void play() {
String hello = mEditText.getText().toString();
mTts.speak(hello, TextToSpeech.QUEUE_FLUSH, null);
}
}
text_to_speech.xml
<?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" >
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:enabled="false"
android:ems="7"
android:gravity="center"
android:text="Play" />
</LinearLayout>
I hope this post is useful to you. kindly share your feedback as comment here.
Comments
Post a Comment