Berikut adalah beberapa tahapan membuat text to speech di android:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" />
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
MainActivity.java
import java.util.Locale;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Button;
public class MainActivity extends Activity implements TextToSpeech.OnInitListener {
private TextToSpeech speech;
private Button speak;
private EditText comments;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
speech = new TextToSpeech(this, this);
speak = (Button) findViewById(R.id.button1);
comments = (EditText) findViewById(R.id.editText1);
speak.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
speak();
}
});
}
@Override
public void onDestroy() {
if (speech != null) {
speech.stop();
speech.shutdown();
}
super.onDestroy();
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = speech.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
speak.setEnabled(true);
speak();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void speak() {
String text = comments.getText().toString();
speech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
No comments:
Post a Comment