Speech recognitionNew
Stream native speech-to-text from Kotlin Multiplatform code on Windows, macOS, Android and iOS, and dictate into a text field.
speech-recognition streams speech-to-text from the platform's own recognizer. It is a Kotlin
Multiplatform module: the same calls work on desktop, Android and iOS.
speech-recognitionDesktop Gradle plugin: RecommendedDesktop window runtime: Not neededmacOS needs a bundle with the microphone and speech usage descriptions.| Platform | Recognizer |
|---|---|
| Windows | SAPI dictation, on-device |
| macOS 11+ | SFSpeechRecognizer with AVAudioEngine |
| Linux | None: isSupported is false |
| Android 8.0+ (API 26) | SpeechRecognizer |
| iOS | SFSpeechRecognizer with AVAudioEngine |
Add the dependency
// commonMain in a KMP project, dependencies { } in a JVM desktop app
implementation("dev.nucleusframework:nucleus.speech-recognition:3.0.0")Start a session
import dev.nucleusframework.speech.SpeechRecognition
if (SpeechRecognition.isSupported) {
val session = SpeechRecognition.start(SpeechRecognitionOptions(locale = "en-US")) { event ->
when (event) {
SpeechEvent.Started -> println("recording")
is SpeechEvent.Transcript -> println("${event.text} (final: ${event.isFinal})")
is SpeechEvent.AudioLevel -> meter.value = event.level
SpeechEvent.Stopped -> println("done")
is SpeechEvent.Error -> println("${event.message} (${event.kind})")
}
}
// Later:
session.stop() // close the microphone; the last words still arrive, then Stopped
session.cancel() // or discard everything; no event follows
}startreturns at once and asks for the permissions itself.Startedmeans the microphone is recording; a refusal arrives asError(PermissionDenied).- A session reports
Started, then any number ofTranscriptandAudioLevelevents, then exactly one terminal event:StoppedorError. A cancelled session reports nothing more. - A partial transcript replaces the current utterance, and a final one commits it. Recognition carries on across utterances until stopped. Speech stays plain text: saying "enter" types "enter".
- One session runs at a time: a second
startthrowsSpeechException(Busy).SpeechRecognition.cancelAll()ends every session, for example when the app quits. SpeechSessionisAutoCloseable:close()cancels it.isActivetells whether it has ended.
The listener runs on a platform thread: the main thread on Android and Apple platforms, a SAPI worker thread on Windows. Hop to the UI thread before touching UI state.
SpeechRecognitionOptions takes a BCP-47 locale (null for the system's speech language) and
preferOnDevice (default true), which uses on-device recognition where the platform has it.
Windows is always on-device.
AudioLevel.level is the microphone amplitude between 0 and 1, for a level meter.
Dictate into a text field
Dictation turns transcripts into text edits without knowing any UI toolkit. Offsets are UTF-16
indices, like String and Compose's TextRange:
var field by remember { mutableStateOf(TextFieldValue()) }
val scope = rememberCoroutineScope()
fun dictate() {
val dictation = Dictation(field.text, field.selection.start, field.selection.end)
SpeechRecognition.start { event ->
if (event !is SpeechEvent.Transcript) return@start
scope.launch { // back on the UI thread
dictation.transcript(event.text, event.isFinal)?.let { edit ->
val text = field.text.replaceRange(edit.start, edit.end, edit.text)
field = TextFieldValue(text, TextRange(edit.start + edit.text.length))
dictation.applied()
}
}
}
}Speech replaces the selection passed to the constructor and goes on from there. Partials revise the current utterance in place, and a space separates dictated words from typed text, except before punctuation, after an opening bracket and between CJK characters.
When the user is about to edit the field, with a keystroke or a click that moves the caret, call
interrupt() first, then settle(text, selectionStart, selectionEnd) once the edit has landed.
Dictation resumes at the caret without losing or repeating a word. Treat an IME composition as an
interruption, and settle only once it commits. Replacement.continues tells a revision of the
previous edit from a new one, to group undo steps. Dictation is not thread-safe: use it from the
UI thread.
Set up each platform
macOS
Recognition needs an app bundle that declares both usage descriptions; a plain ./gradlew run
reports PermissionDenied. A hardened-runtime app, which every notarized app is, also needs the
com.apple.security.device.audio-input entitlement, which the plugin's defaults do not grant:
macOS {
infoPlist {
extraKeysRawXml = """
<key>NSMicrophoneUsageDescription</key>
<string>Dictation uses the microphone.</string>
<key>NSSpeechRecognitionUsageDescription</key>
<string>Dictation transcribes your speech.</string>
""".trimIndent()
}
entitlementsFile.set(project.file("entitlements.plist")) // + device.audio-input
}entitlementsFile replaces the defaults, so keep the JVM keys next to the new one. See Configure
macOS entitlements. Events arrive on the
main dispatch queue, which the Tao event loop drains: a headless app without a Cocoa run loop on
the main thread receives none.
Windows
Install a Windows speech recognition language and allow microphone access for desktop apps in Settings → Privacy & security → Microphone. No package identity is needed.
Android
The library manifest declares RECORD_AUDIO and the RecognitionService query, and handles the
runtime permission prompt. A session ends when its activity pauses.
iOS
Declare NSMicrophoneUsageDescription and NSSpeechRecognitionUsageDescription; both
permissions are requested for you. Recognition prefers on-device models and restarts its task
before Apple's one-minute limit.
Handle errors
SpeechEvent.Error.kind and SpeechException.kind are a SpeechErrorKind. An Error message
comes from the platform and is already worded for end users.
| Value | Meaning |
|---|---|
PermissionDenied | Permission refused, or the app lacks the usage descriptions needed to ask. Point the user to the privacy settings |
Unavailable | No audio input or recognizer here; retrying will not help |
Language | The recognizer does not support the requested locale |
Audio | The microphone is missing, busy or changed mid-session; starting again likely works |
Busy | Another session is active |
Other | Anything else the platform reported |
API reference
| Symbol | Notes |
|---|---|
SpeechRecognition.isSupported | Cheap and permission-free: hide a dictation button when false |
SpeechRecognition.engineName | Short, stable recognizer name |
SpeechRecognition.start(options, listener): SpeechSession | Throws SpeechException when the session cannot begin |
SpeechRecognition.cancelAll() | Cancels every active session |
SpeechSession.stop() / cancel() / close() / isActive | Stop with the last result / discard / same as cancel / still running |
SpeechEvent | Started, Transcript(text, isFinal), AudioLevel(level), Stopped, Error(kind, message) |
Dictation(text, selectionStart, selectionEnd) | transcript, applied, interrupt, settle, isInterrupted |
Replacement | start, end, text, continues |
What's next
- Location: the device's position, from the same KMP code.
- Share sheet: the system share sheet.
- Sandboxing: macOS entitlements.
Last updated on
Location
Read the device's position from Kotlin Multiplatform code, with one API on Windows, macOS, Linux, Android, iOS and the web.
Authentication
Ask the OS to confirm the device owner is present, with Touch ID, Face ID, Windows Hello, Android BiometricPrompt or polkit, from Kotlin Multiplatform code.