问题描述
我正在使用 TextToSpeech 类的 android,但是当我 instantiate
它在方法中 TTS 不起作用
但如果我在 中声明它>onCreate()
方法有效.(请注意,我的应用在两种情况下都运行)
I am using TextToSpeech class of android but when I instantiate
it inside a method TTS doesnt work
but if I declared it within onCreate()
method it works.(Note that my app runs in both cases)
为什么会这样?
我听说在内部实例化类是一种很好的做法方法,如果没有其他方法正在使用它.
更新:
代码:
TextToSpeech t1;
public void speak(View v){
Log.i(TAG,"speak method");
t1=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR){
t1.setLanguage(Locale.UK);
}
}
});
t1.speak("I m speaking out dude",TextToSpeech.QUEUE_FLUSH,null);
}
推荐答案
创建 TextToSpeech 实例后,初始化文本转语音引擎.这是一个异步操作.OnInitListener(第二个参数)在初始化完成后被调用.根据初始化状态,状态可以是 TextToSpeech.SUCCESS 或 TextToSpeech.ERROR.
After creating the instance of TextToSpeech, it Initializes text-to-speech engine. This is an asynchronous operation. The OnInitListener (second argument) is called after initialization completes. The status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR based on the initialization status.
由于它是异步的,所以需要一些时间来完成它的操作.
As it is an asynchronous, it takes some time to complete its operation.
所以,这是答案,
当您在 onCreate 创建实例时,引擎有时间在您调用speak(String str)"之前进行初始化并且它可以工作.但是当您在方法本身内部创建实例时,TTS 引擎没有时间在 Speak 之前完成其初始化.
When you create the instance at onCreate, the engine gets time to initialize before you call "speak(String str)" and it works. But when you create the instance inside the method itself, TTS engine does not get time to complete its initialization before Speak.
这篇关于在哪里实例化 TextToSpeech 类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!