我对文字到语音有一种奇怪的体验。
看我的代码:
Button b;
TextView title, body;
TextToSpeech tts;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popups);
b = (Button) findViewById(R.id.buttonok);
title = (TextView) findViewById(R.id.textViewtitle);
body = (TextView) findViewById(R.id.textViewbody);
b.setText("ok");
title.setText(Receive.address);
body.setText(Receive.body);
tts = new TextToSpeech(Popup.this, new TextToSpeech.OnInitListener() {
public void onInit(int status) {
// TODO Auto-generated method stub
if (status != TextToSpeech.ERROR) {
tts.setLanguage(Locale.US);
}
}
});
play();//this is not working??!!i don't know why
b.performClick();//even this is not working
/* but when i click this button it works??? how and why?*/
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
play(); // Popup.this.finish();
}
});
}
private void play() {
// TODO Auto-generated method stub
tts.speak(Receive.body, TextToSpeech.QUEUE_FLUSH, null);
}
我的文字到语音只有在我点击按钮时才能正常工作,但每当我没有点击这个按钮并在正常代码中写入tts.speak()时它就不起作用了......为什么?
问候查理
答案 0 :(得分:4)
您必须等待onInit
被调用才能开始speak
。在您的代码中,您可以在声明后立即调用play()。 onInit是一个回调,它需要一些时间才能被调用。如果在按钮出现后立即单击按钮,则有时会因为onInit未被调用而失败。您应该有一个班级成员boolean mIsReady
并在 onInit 中将其设置为true。在您的play()
方法
private void play() {
// TODO Auto-generated method stub
if (mIsReady) {
tts.speak(Receive.body, TextToSpeech.QUEUE_FLUSH, null);
}
}
答案 1 :(得分:2)
b.performClick();//even this is not working
/* but when i click this button it works??? how and why?*/
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
play(); // Popup.this.finish();
}
});
在设置b.performClick()
之前,您正在使用setOnClickListener
执行点击。此外,您最好使用onResume()
方法进行此类调用。 OnCreate旨在用于绑定视图和准备活动。在向前台显示用户视图之前,将调用onResume()
方法,这样就可以放置此代码了。
查看活动生命周期。