我使用的是android.speech.SpeechRecognizer
,遇到了一个问题,即使在我调用了它的stopListening()
、cancel()
和destroy()
方法后,它也会发出独特的叮当声。
以下是我如何在MainActivity.kt
中创建和销毁SpeechRecognizer
。
private fun startSpeechRecognition() {
Log.e(TAG, "At start of startSpeechRecognition()")
if (recognizer == null) {
recognizer = SpeechRecognizer.createSpeechRecognizer(this)
Log.e(TAG, "Creating new recognizer: $recognizer")
recognizer?.setRecognitionListener(Listener())
}
val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
intent.putExtra(
RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM
)
Log.e(TAG, "Starting listening")
recognizer?.startListening(intent)
}
private fun closeRecognizer() {
Log.e(TAG, "At start of closeRecognizer()")
recognizer?.run {
Log.e(TAG, "Stopping recognizer: $this")
stopListening()
cancel()
destroy()
recognizer = null
} ?: Log.e(TAG, "Recognizer already null")
}
这是我的日志:
E/voice.assistan: Unknown bits set in runtime_flags: 0x8000
E/MainActivity: At start of closeRecognizer()
E/MainActivity: Recognizer already null
E/MainActivity: At start of startSpeechRecognition()
E/MainActivity: Creating new recognizer: android.speech.SpeechRecognizer@573d161
E/MainActivity: Starting listening
E/MainActivity: At start of closeRecognizer()
E/MainActivity: Stopping recognizer: android.speech.SpeechRecognizer@573d161
E/SpeechRecognizer: not connected to the recognition service
E/SpeechRecognizer: not connected to the recognition service
E/MainActivity: At start of closeRecognizer()
E/MainActivity: Recognizer already null
我正在运行Android 10的Pixel 2上测试代码,并使用minSdkVersion
21和targetSdkVersion
28进行编译。
有人能告诉我我可能做错了什么,或者库中是否有错误吗
我目前有一个笨拙的解决方法,在关闭识别器后将媒体音频流静音。
您确定需要调用SpeechRecognizer.cancel()
吗?根据这个答案,调用CCD_ 10就足够了。
还要注意日志中没有connected to the recognition service
错误,这表明SpeechRecognizer出现了问题。您可以尝试删除对cancel()
的调用,并检查错误是否消失。