我想在我的应用程序中使用TTS。首先,我正在尝试运行一些示例,但每次TTS都无法在我的设备上运行。在示例中,我有代码:
MainActivity:
package com.example.tts;
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 MainActivity extends Activity implements TextToSpeech.OnInitListener {
private TextToSpeech textToSpeech;
private Button button;
private EditText inputText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
inputText = (EditText) findViewById(R.id.inputText);
textToSpeech = new TextToSpeech(this, this);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
convertTextToSpeech();
}
});
convertTextToSpeech();
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("error", "This Language is not supported");
} else {
convertTextToSpeech();
}
} else {
Log.e("error", "Initilization Failed!");
}
}
@Override
public void onDestroy() {
textToSpeech.shutdown();
super.onDestroy();
}
private void convertTextToSpeech() {
//String text = "test";
String text = inputText.getText().toString();
if (null == text || "".equals(text)) {
text = "Please give some input.";
}
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
activity_main.xml中:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TextToSpeechActivity" >
<EditText
android:id="@+id/inputText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="42dp"
android:layout_marginTop="28dp"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/inputText"
android:layout_below="@+id/inputText"
android:layout_marginTop="14dp"
android:text="Speak" />
</RelativeLayout>
输入单词并单击按钮后,应用程序什么也没说。 有谁知道如何解决它?提前谢谢。