The app uses the ActivityResultContracts.StartActivityForResult() contract to launch the system’s speech recognition activity and receive the transcribed text.
1
Register the activity result launcher
Create a launcher that handles the speech recognition result using rememberLauncherForActivityResult.
val speechRecognizerLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.StartActivityForResult(), onResult = { result -> val spokenText = result.data?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)?.firstOrNull() if (spokenText != null) { prompt = spokenText // Update prompt with recognized text } else { Toast.makeText(context, "Failed to recognize speech", Toast.LENGTH_SHORT).show() } })
The launcher extracts the first result from EXTRA_RESULTS and updates the UI state with the recognized text.
2
Create the recognition intent
Build an intent with RecognizerIntent.ACTION_RECOGNIZE_SPEECH and configure the language model and locale.
val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)intent.putExtra( RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault())intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak now...")
LANGUAGE_MODEL_FREE_FORM is optimized for free-form speech rather than search queries.
3
Launch the recognizer
Call the launcher with the configured intent to start speech recognition.
speechRecognizerLauncher.launch(intent)
This opens the system’s speech recognition dialog where users can speak their input.
The speech recognizer launcher must be created at the composable level using rememberLauncherForActivityResult. You cannot create it inside the button’s onClick handler.
Always check for RECORD_AUDIO permission before launching the speech recognizer. See the permissions guide for details.