Android上的TextToSpeech初始化-如果失败,该怎么办? [英] TextToSpeech initialization on Android -- what if it fails?
问题描述
在Android中,如果TextToSpeech实例未能初始化(调用的回调指示TextToSpeech引擎初始化完成,则返回TextToSpeech.ERROR),这是否意味着对该实例的后续尝试方法调用将导致空指针异常?/p>
示例...
我们初始化对象:
t1 = new TextToSpeech(getApplicationContext(),new TextToSpeech.OnInitListener(){@Overridepublic void onInit(int status){如果(状态== TextToSpeech.ERROR){Log.i("XXX",初始化TTS时出错");}}});
...假设初始化失败,但是接下来我们要做类似的事情:
t1.speak("hello");
会崩溃吗?还是什么都不说?我问的原因是,如果它确实崩溃了,那么显然我将不得不在所有地方放置空检查.
此外,我不能自己找出原因的原因是我不知道如何模拟错误.
感谢您有任何先验知识.
对于您的主要问题,请阅读 speak()
方法的文档(请参阅文档),它希望作为第三个参数 String engine
并在其中放置无效的程序包名称.然后可能会导致错误.(或禁用/卸载设备/仿真器上的所有TTS引擎)
关于构造函数的重要注意事项是:
在失败的情况下,可以在完全构造TextToSpeech实例之前立即调用侦听器.
因此,除非状态为 SUCCESS
,否则您不应该在监听器中触摸您的 tts
(当然,您可以使用 tts
之后,如您的示例所示),因为它甚至可能尚未分配/初始化.
In Android, if a TextToSpeech instance fails to initialize (the callback invoked indicating the completion of the TextToSpeech engine initialization returns TextToSpeech.ERROR), does that mean that subsequent attempted method calls to that instance will result in null pointer exceptions?
Example...
We initialize the object:
t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status == TextToSpeech.ERROR) {
Log.i("XXX", "There was an error initializing the TTS");
}
}
});
... let's say the init fails, but we then go on to do something like:
t1.speak("hello");
Will this crash... or just say nothing? The reason I ask is that if it does crash, then obviously I would have to put null checks everywhere.
Also, the reason I can't just find out for myself is that I don't know how to simulate the error.
Thanks for any prior knowledge.
For your main question read the docs of the speak()
method (here):
This method is asynchronous, i.e. the method just adds the request to the queue of TTS requests and then returns.
So unless your tts
instance is null
, it shouldn't throw any exception or crash the app, but just return the error code.
Also, the reason I can't just find out for myself is that I don't know how to simulate the error.
Try to use constructor (see docs) that expects as third parameter String engine
and put invalid package name there. It should probably result in error then. (or disable/uninstall all TTS engines on your device/emulator)
Important thing to note regarding constructor is:
In a case of a failure the listener may be called immediately, before TextToSpeech instance is fully constructed.
So unless the status is SUCCESS
, you shouldn't touch your tts
in the listener (of course you can use the tts
afterwards as in your example) because it might not even be assigned / initialized yet.
这篇关于Android上的TextToSpeech初始化-如果失败,该怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!