-
Notifications
You must be signed in to change notification settings - Fork 0
feat(android/voice): on-device STT and LLM via SpeechRecognizer + Gemini Nano #27
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
bb7f5ef
feat(android/voice): on-device STT and LLM via SpeechRecognizer + Gem…
tstapler b72c420
fix(android): bump kmp minSdk to 26 for genai-prompt library
tstapler dc66ebe
fix(ios): replace Dispatchers.IO with PlatformDispatcher.DB in common…
tstapler fd74bb3
fix(ci): exclude Kotlin IC state from Gradle home cache in Android job
tstapler edbf46c
fix: address all PR review comments
Copilot 9c0825e
fix: guard against early cancellation before SpeechRecognizer is created
Copilot d37204f
chore: merge main into stelekit-voice
tstapler 3eea2ba
Merge remote-tracking branch 'origin/stelekit-voice' into stelekit-voice
tstapler 3aeb251
chore: merge main into stelekit-voice (v0.9.5)
tstapler f4bc24b
chore: merge main into stelekit-voice (v0.10.0)
tstapler File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
132 changes: 132 additions & 0 deletions
132
kmp/src/androidMain/kotlin/dev/stapler/stelekit/voice/AndroidSpeechRecognizerProvider.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,132 @@ | ||
| // Copyright (c) 2026 Tyler Stapler | ||
| // SPDX-License-Identifier: Elastic-2.0 | ||
| package dev.stapler.stelekit.voice | ||
|
|
||
| import android.content.Context | ||
| import android.content.Intent | ||
| import android.os.Bundle | ||
| import android.os.Handler | ||
| import android.os.Looper | ||
| import android.speech.RecognitionListener | ||
| import android.speech.RecognizerIntent | ||
| import android.speech.SpeechRecognizer | ||
| import android.util.Log | ||
| import kotlinx.coroutines.Dispatchers | ||
| import kotlinx.coroutines.flow.Flow | ||
| import kotlinx.coroutines.flow.MutableStateFlow | ||
| import kotlinx.coroutines.flow.asStateFlow | ||
| import kotlinx.coroutines.suspendCancellableCoroutine | ||
| import kotlinx.coroutines.withContext | ||
| import kotlin.coroutines.resume | ||
|
|
||
| private const val TAG = "AndroidSpeechRecognizer" | ||
|
|
||
| class AndroidSpeechRecognizerProvider(private val context: Context) : DirectSpeechProvider { | ||
|
|
||
| companion object { | ||
| fun isAvailable(context: Context): Boolean = | ||
| SpeechRecognizer.isRecognitionAvailable(context) | ||
| } | ||
|
|
||
| private val _amplitudeFlow = MutableStateFlow(0f) | ||
| override val amplitudeFlow: Flow<Float> = _amplitudeFlow.asStateFlow() | ||
|
|
||
| @Volatile private var activeRecognizer: SpeechRecognizer? = null | ||
| private val mainHandler = Handler(Looper.getMainLooper()) | ||
|
|
||
| override suspend fun listen(): TranscriptResult = suspendCancellableCoroutine { cont -> | ||
| cont.invokeOnCancellation { | ||
| mainHandler.post { | ||
| activeRecognizer?.let { | ||
| it.cancel() | ||
| it.destroy() | ||
| activeRecognizer = null | ||
| } | ||
| _amplitudeFlow.value = 0f | ||
| } | ||
| } | ||
|
|
||
| mainHandler.post { | ||
| var recognizer: SpeechRecognizer? = null | ||
| try { | ||
| recognizer = SpeechRecognizer.createSpeechRecognizer(context) | ||
| activeRecognizer = recognizer | ||
|
|
||
| // Guard against cancellation that fired before this post ran | ||
| if (!cont.isActive) { | ||
| recognizer.destroy() | ||
| activeRecognizer = null | ||
| return@post | ||
| } | ||
|
|
||
| recognizer.setRecognitionListener(object : RecognitionListener { | ||
| override fun onReadyForSpeech(params: Bundle?) {} | ||
| override fun onBeginningOfSpeech() {} | ||
| override fun onBufferReceived(buffer: ByteArray?) {} | ||
| override fun onEndOfSpeech() {} | ||
| override fun onEvent(eventType: Int, params: Bundle?) {} | ||
| override fun onPartialResults(partialResults: Bundle?) {} | ||
|
|
||
| override fun onRmsChanged(rmsdB: Float) { | ||
| // Map roughly -2..10 dB → 0..1 | ||
| _amplitudeFlow.value = ((rmsdB + 2f) / 12f).coerceIn(0f, 1f) | ||
| } | ||
|
|
||
| override fun onResults(results: Bundle?) { | ||
| _amplitudeFlow.value = 0f | ||
| activeRecognizer = null | ||
| recognizer.destroy() | ||
| if (!cont.isActive) return | ||
| val text = results | ||
| ?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION) | ||
| ?.firstOrNull() | ||
| Log.d(TAG, "onResults: text=${text?.take(80)}") | ||
| if (text.isNullOrBlank()) cont.resume(TranscriptResult.Empty) | ||
| else cont.resume(TranscriptResult.Success(text)) | ||
| } | ||
|
|
||
| override fun onError(error: Int) { | ||
| _amplitudeFlow.value = 0f | ||
| activeRecognizer = null | ||
| recognizer.destroy() | ||
| if (!cont.isActive) return | ||
| Log.w(TAG, "onError: code=$error") | ||
| cont.resume(mapError(error)) | ||
| } | ||
| }) | ||
|
|
||
| val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply { | ||
| putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM) | ||
| putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, true) | ||
| putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1) | ||
| putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS, 3_000L) | ||
| putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS, 1_500L) | ||
| } | ||
| recognizer.startListening(intent) | ||
| } catch (t: Throwable) { | ||
| _amplitudeFlow.value = 0f | ||
| activeRecognizer = null | ||
| recognizer?.destroy() | ||
| Log.w(TAG, "Failed to start speech recognition", t) | ||
| if (cont.isActive) { | ||
| cont.resume(mapError(SpeechRecognizer.ERROR_CLIENT)) | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| override suspend fun stopListening() { | ||
| withContext(Dispatchers.Main) { | ||
| activeRecognizer?.stopListening() | ||
| } | ||
| } | ||
|
|
||
| private fun mapError(error: Int): TranscriptResult = when (error) { | ||
| SpeechRecognizer.ERROR_NO_MATCH, | ||
| SpeechRecognizer.ERROR_SPEECH_TIMEOUT -> TranscriptResult.Empty | ||
| SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS -> TranscriptResult.Failure.PermissionDenied | ||
| SpeechRecognizer.ERROR_NETWORK, | ||
| SpeechRecognizer.ERROR_NETWORK_TIMEOUT -> TranscriptResult.Failure.NetworkError | ||
| else -> TranscriptResult.Failure.ApiError(error, "Speech recognition error (code $error)") | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
deviceLlmAvailableis resolved asynchronously inLaunchedEffect, butvoicePipelineis only built once and then rebuilt only viaonRebuildVoicePipeline. If a user already has “Use on-device LLM” enabled, they’ll still start with the cloud/no-op pipeline until they manually open Settings and hit Save. Consider rebuilding the pipeline automatically whendeviceLlmAvailableflips to true (or passmlKitProviderregardless ofdeviceLlmAvailableand let the provider handle unsupported/downloading states).There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed in commit edbf46c: added
LaunchedEffect(deviceLlmAvailable)in MainActivity that callsonRebuildVoicePipeline()whenever the flag flips, so the pipeline is rebuilt automatically without requiring a manual settings round-trip.