android - 如何防止Android SpeechRecognizer被破坏后发出声音?

标签 android kotlin android-speech-api

我正在使用 android.speech.SpeechRecognizer 我有一个问题,即使在我调用它之后它也会发出独特的 clang stopListening() , cancel() , 和 destroy()方法。

下面是我如何创建和销毁 SpeechRecognizer MainActivity.kt .

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() 吗?根据this调用 SpeechRecognizer.destroy() 可能就足够了。

另请注意日志中的未连接到识别服务 错误,表明 SpeechRecognizer 出现问题。您可以尝试移除 cancel() 的调用并检查错误是否消失。

关于android - 如何防止Android SpeechRecognizer被破坏后发出声音?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61469946/

相关文章:

android - mutableStateListOf 反向期间的 ConcurrentModificationException

json - Jackson Kotlin - 反序列化 JsonNode

android - 如何为 android 正确使用 strerror_r()

android - 在android中使用媒体播放器时如何避免音频剪辑重复之前的延迟

java - Android中使用正则表达式处理字符串

java - TextToSpeech 无法正确停止

android - SpeechRecognizer.isRecognitionAvailable() 在 Android 11 中始终为 false

android - 百分号导致 Twitter 应用程序崩溃

android - Kotlin如何调用作为参数传递的方法

android - 如何在android中等待语音识别的结果?