所以现在当我运行应用程序时,函数showLabel首先运行,而不是初始化TTS。我总是得到一个错误,tts为null。有没有更好的方法来解决这个问题?我应该在onInit上的showLabel上移动我的代码吗?它也有一个参数。目标是firstObject
将成为TTS的文本。当我尝试在Oninit中添加.speak时它可以工作,但是当它在外面时会导致null错误。任何帮助都会感激不尽!
private var tts: TextToSpeech? = null
var firstObject = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_live_preview)
tts = TextToSpeech(this, this)
fun showLabel(labels: List<FirebaseVisionImageLabel>?) {
firstObject = labels!!.first().text
Log.d(TAG, firstObject)
tts!!.speak(firstObject, TextToSpeech.QUEUE_FLUSH, null, "")
}
override fun onInit(status: Int) {
if (status == TextToSpeech.SUCCESS) {
// set US English as language for tts
val result = tts!!.setLanguage(Locale.US)
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS","The Language specified is not supported!")
} else {
Log.d("TTS", "Initilization Successful")
tts!!.speak("This is a test", TextToSpeech.QUEUE_FLUSH, null, "") // works
cameraSource?.setMachineLearningFrameProcessor(ImageLabelingProcessor())
}
} else {
Log.e("TTS", "Initilization Failed!")
}
}
你不能在尚未初始化的TTS对象上调用speak()。
由于你在showLabel()函数中有speak(),这意味着你不能在初始化TTS之前调用showLabel()。
你可以做的是创建一个类级别的布尔变量,ttsIsInitialized,并将其设置为false,直到TTS初始化...从onInit()内部设置为true。
然后,在showLabel()中,你要做的第一件事是检查布尔值是否仍为假,然后返回/什么都不做。