0

Consider this Kotlin code to init a Google speech recognizer:

            recognizerIntent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
            .apply {
                putExtra(
                    RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                    RecognizerIntent.LANGUAGE_MODEL_FREE_FORM
                )
                putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US")
                putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3)
                putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, true)
            }

This used to work up until SDK 32 but is failing since. The crux of the problem is the last put extra, EXTRA_PREFER_OFFLINE. If you don't include it, the recognizer is set up, but not always.

Apparently some OEMs include online recognitions and others don't, whereas others (inc. Pixel) enable users to control online/offline in their preferences.

Does anyone know of a way to detect the status of the device, and accordingly add this put extra for devices with SDK > 32?

Thanks!

1 Answer 1

0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { // API 31 (Android 12)
            if (SpeechRecognizer.isOnDeviceRecognitionAvailable(context)) {
                putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, true)
            }
        } else {
          
            putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, true)
        }

Try this. I have used it like this

val recognizer = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && SpeechRecognizer.isOnDeviceRecognitionAvailable(context)) {
    SpeechRecognizer.createOnDeviceSpeechRecognizer(context)
} else {
    SpeechRecognizer.createSpeechRecognizer(context)
}
recognizer.setRecognitionListener(yourListener)
recognizer.startListening(createRecognizerIntent(context))
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Pratik. isOnDeviceRecognitionAvailable() fails for me on an emulator with SDK 35 (I don't have a real device that supports this level.) I get error code 13, whatever that is. ChatGPT insists that Google did not provide a method to detect whether offline is available on the device and, if so, whether the user enabled it in Settings. The documentation about this method leaves something to be desired. ChatGPT recommends try-and-catch but the user experience is ugly.
Okay. Code 13 means no match found. I don’t think this is a code issue. I suggest trying it on a real device — it should work there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.