Nucleus
OS integration

Speech recognitionNew

Stream native speech-to-text from Kotlin Multiplatform code on Windows, macOS, Android and iOS, and dictate into a text field.

View as Markdown

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-recognitionmacOSWindowsAndroidiOSDesktop Gradle plugin: RecommendedDesktop window runtime: Not neededmacOS needs a bundle with the microphone and speech usage descriptions.
PlatformRecognizer
WindowsSAPI dictation, on-device
macOS 11+SFSpeechRecognizer with AVAudioEngine
LinuxNone: isSupported is false
Android 8.0+ (API 26)SpeechRecognizer
iOSSFSpeechRecognizer with AVAudioEngine

Add the dependency

build.gradle.kts
// 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
}
  • start returns at once and asks for the permissions itself. Started means the microphone is recording; a refusal arrives as Error(PermissionDenied).
  • A session reports Started, then any number of Transcript and AudioLevel events, then exactly one terminal event: Stopped or Error. 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 start throws SpeechException(Busy). SpeechRecognition.cancelAll() ends every session, for example when the app quits.
  • SpeechSession is AutoCloseable: close() cancels it. isActive tells 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:

build.gradle.kts
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.

ValueMeaning
PermissionDeniedPermission refused, or the app lacks the usage descriptions needed to ask. Point the user to the privacy settings
UnavailableNo audio input or recognizer here; retrying will not help
LanguageThe recognizer does not support the requested locale
AudioThe microphone is missing, busy or changed mid-session; starting again likely works
BusyAnother session is active
OtherAnything else the platform reported

API reference

SymbolNotes
SpeechRecognition.isSupportedCheap and permission-free: hide a dictation button when false
SpeechRecognition.engineNameShort, stable recognizer name
SpeechRecognition.start(options, listener): SpeechSessionThrows SpeechException when the session cannot begin
SpeechRecognition.cancelAll()Cancels every active session
SpeechSession.stop() / cancel() / close() / isActiveStop with the last result / discard / same as cancel / still running
SpeechEventStarted, Transcript(text, isFinal), AudioLevel(level), Stopped, Error(kind, message)
Dictation(text, selectionStart, selectionEnd)transcript, applied, interrupt, settle, isInterrupted
Replacementstart, end, text, continues

What's next

Was this page helpful?
Edit on GitHub

Last updated on