cap*_*com 5 android text-to-speech
我已经按照几个教程,但我遇到了同样的问题.首先,这是我的简单代码:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,请注意onCreate()我已经评论过的第一个发言,以及我已经评论过的第二个发言onStart().基于我在LogCat中收到的内容,这一点很明显.由于某种原因,它们在完成初始化之前被调用reader.因此,我正确使用此speak()功能的唯一方法是在初始化之后立即放置函数,确保在其自己的方法中完成.
所以我在想,如果有任何的方式来等待初始化完成,然后运行speak()中onCreate或onStart().
小智 4
你可以这样做:
@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.");
}
}
Run Code Online (Sandbox Code Playgroud)
这不是很好,但是很有效。我希望有人能找到更好的解决方案......
| 归档时间: |
|
| 查看次数: |
2498 次 |
| 最近记录: |