Overview
VoiceRecognitionScreen is the primary composable function that implements the voice recognition interface. It provides a text input field and a button that triggers Android’s speech recognition API.
Function signature
Parameters
Optional modifier for customizing the layout and appearance of the composable. Typically used to apply padding from the parent Scaffold.
Features
State management
The composable maintains local state for the text prompt usingremember and mutableStateOf:
Speech recognizer launcher
Implements an activity result launcher for handling speech recognition results:The recognized speech text extracted from the recognition result. Returns null if speech recognition fails.
Voice recognition trigger
The “Speak” button initiates the speech recognition process with permission checks:UI components
The screen consists of:- BasicTextField - An editable text field with a placeholder that displays “Type or speak your message…” when empty
- Speak Button - Triggers the speech recognition flow or requests microphone permissions if not granted
Layout structure
The composable automatically requests the
RECORD_AUDIO permission if it hasn’t been granted when you click the “Speak” button.Required permissions
This composable requires the following Android permission:android.permission.RECORD_AUDIO- Required for accessing the device microphone for speech recognition
Intent extras
When launching the speech recognizer, the following extras are configured:Set to
LANGUAGE_MODEL_FREE_FORM for unrestricted speech recognitionUses the device’s default locale for language-specific recognition
Displays “Speak now…” as a prompt to the user during recognition