我的Android应用程序中有一个文本到语音功能,适用于onClick事件,活动开始时出现问题,文本到语音的开始没有点击按钮,是否有一行代码我可以放入为了阻止这种情况发生,谢谢你。
package com.androidhive.texttospeech;
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.TextView;
public class AndroidTextToSpeechActivity extends Activity implements
TextToSpeech.OnInitListener {
/** Called when the activity is first created. */
private TextToSpeech tts;
private Button button1;
private TextView txtText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tts = new TextToSpeech(this, this);
button1 = (Button) findViewById(R.id.button1);
txtText = (TextView) findViewById(R.id.txtText);
// button on click event
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
speakOut();
}
});
}
@Override
public void onDestroy() {
// Don't forget to shutdown!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
@Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
// tts.setPitch(5); // set pitch level
// tts.setSpeechRate(2); // set speech speed rate
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
button1.setEnabled(true);
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed");
}
}
private void speakOut() {
String text = txtText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
答案 0 :(得分:0)
我在onInit()中看到了这些代码,它们将在TextToSpeech实例化并成功初始化后调用。在这里看到speakOut()?这就是造成问题的原因。
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
button1.setEnabled(true);
speakOut();
}
答案 1 :(得分:0)
发生这种情况的原因是因为你调用speakOut#在onInit()方法中,删除speakOut():
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
button1.setEnabled(true);
// speakOut();
}