正如标题所暗示的那样,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)
}
...