我看了几个教程,但我遇到了同样的问题。首先,这是我的简单代码:
import java.util.Locale;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
public class AchievementsActivity extends Activity implements OnInitListener {
TextToSpeech reader;
Locale canada;
boolean readerInit = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
canada = Locale.ENGLISH;
reader = new TextToSpeech(this, this);
//speak();
// while (reader.isSpeaking()) {} //waiting for reader to finish speaking
}
@Override
public void onStart() {
super.onStart();
//speak();
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
reader.setLanguage(canada);
reader.setPitch(0.9f);
Log.e("Init", "Success");
readerInit = true;
speak();
}
else
System.out.println("Something went wrong.");
}
public void speak() {
reader.speak("You currently have no achievements.", TextToSpeech.QUEUE_FLUSH, null);
}
}
现在,请注意 onCreate()
中的第一个 speak,我已将其注释掉,而 onStart()
中的第二个 speak 我也已将其注释掉。根据我在 LogCat 中收到的内容,这样做的原因很明显。由于某些原因,它们在 reader
的初始化完成之前被调用。因此,我唯一能正常工作的方法是在初始化确保在其自己的方法中完成后立即放置 speak()
函数。
所以我想知道有没有办法等待初始化完成,然后在onCreate
或onStart()<中运行
.speak()
/
最佳答案
你可以这样做:
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
reader.setLanguage(canada);
reader.setPitch(0.9f);
Log.e("Init", "Success");
readerInit = true;
// wait a little for the initialization to complete
Handler h = new Handler();
h.postDelayed(new Runnable() {
@Override
public void run() {
// run your code here
speak();
}
}, 400);
}
else {
System.out.println("Something went wrong.");
}
}
它不是很好,但是很管用。我希望有人会找到更好的解决方案...
关于android - 文本转语音未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14563098/