6

正如标题所暗示的那样,SpeechRecognizer.isRecognitionAvailable()在 Android 11 中返回 false,我不确定为什么会这样,因为设备 (Pixel 3 XL) 配备了识别语音的功能。该文档并未表明它在 API v30 中发生了更改。奇怪的是,即使isRecognitionAvailable是假的,我仍然可以成功获得 STT 提示。下面是说明这一点的示例代码。为什么 isRecognitionAvailable 检查总是假的?代码无论如何都不完整,但我添加了重要的相关部分:

AndroidManifest.xml
...
<uses-permission android:name="android.permission.RECORD_AUDIO" />
...
MainActivity.kt
...
override fun onCreate(savedInstanceState: Bundle?) {
...
    if(ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
        if(shouldShowRequestPermissionRationale(Manifest.permission.RECORD_AUDIO)) { //rationale prompt
        }
        val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()
        ){ isGranted: Boolean ->
            if(isGranted) { checkSTT() }
            else { //error perms not granted
            }
        requestPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
    } else { checkSTT() }
}

private fun checkSTT() {
    if(SpeechRecognizer.isRecognitionAvailable(this)) { runSTT() }
    else { runSTT() //Run anyway because isRecognitionAvailable is always false and STT works anyway?
    }
}

private fun runSTT() {
    //Yes, I know this is deprecated
    val sttIntent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
    sttIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
    sttIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.US)
    startActivityForResult(sttIntent, 1)
}
...
4

1 回答 1

11

我想出了解决方案。出于某种原因,从 API v30 开始,您必须将以下内容添加到 Manifest 文件中SpeechRecognizer.isRecognitionAvailable(Context)才能返回 true。我的测试发现它仅在放置在<application>标签之外时才有效,即使它抱怨“此处不允许元素查询”。添加suppress AndroidElementNotAllowed以删除警告。

<!--suppress AndroidElementNotAllowed -->
<queries>
    <intent>
        <action android:name="android.speech.RecognitionService" />
    </intent>
</queries>
<application...
于 2020-11-08T20:57:20.800 回答