Skip to content

Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.

feat: implement audio muting for STT sessions and refactor continuous listening logic in SttEngine

Rishabh Bajpaie03079f43925
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index ae7e07e..edf289d 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -43,6 +43,7 @@
<!-- Tier 0–2: device control (normal / special-access) -->
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />
+ <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
diff --git a/app/src/main/java/com/gotcha/audio/SttEngine.kt b/app/src/main/java/com/gotcha/audio/SttEngine.kt
index 5543093..7a29363 100644
--- a/app/src/main/java/com/gotcha/audio/SttEngine.kt
+++ b/app/src/main/java/com/gotcha/audio/SttEngine.kt
@@ -2,6 +2,7 @@ package com.gotcha.audio
import android.content.Context
import android.content.Intent
+import android.media.AudioManager
import android.media.MediaRecorder
import android.os.Bundle
import android.os.Handler
@@ -9,6 +10,7 @@ import android.os.Looper
import android.speech.RecognitionListener
import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
+import android.util.Log
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@@ -42,6 +44,10 @@ class SttEngine(
private var currentRecorder: MediaRecorder? = null
private var currentAudioFile: File? = null
+ // Audio muting state
+ private val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as android.media.AudioManager
+ private var isMutedForRestart = false
+
// Android STT state
private val mainHandler = Handler(Looper.getMainLooper())
private var currentRecognizer: SpeechRecognizer? = null
@@ -52,6 +58,9 @@ class SttEngine(
private var isContinuousListening = false
private val continuousTranscript = StringBuilder()
+ /** Latest partial result from the current recognizer segment (not yet finalized). */
+ private var currentPartialResult = ""
+
/** The models available from the API (empty if provider is Android). */
var apiSttModels: List<AudioModel> = emptyList()
private set
@@ -119,75 +128,170 @@ class SttEngine(
listenGate = CompletableDeferred<String>()
isContinuousListening = true
continuousTranscript.clear()
+ currentPartialResult = ""
+ muteBeep()
mainHandler.post { startContinuousListeningCycle() }
return true
}
private fun startContinuousListeningCycle() {
- if (!isContinuousListening) return
- val recognizer = SpeechRecognizer.createSpeechRecognizer(context)
- currentRecognizer = recognizer
- recognizer.setRecognitionListener(object : RecognitionListener {
- override fun onReadyForSpeech(params: Bundle?) {}
- override fun onBeginningOfSpeech() {}
- override fun onRmsChanged(rmsdB: Float) {}
- override fun onBufferReceived(buffer: ByteArray?) {}
- override fun onEndOfSpeech() {}
- override fun onError(error: Int) {
- currentRecognizer?.destroy()
- currentRecognizer = null
- if (isContinuousListening) {
- mainHandler.post { startContinuousListeningCycle() }
- } else {
- listenGate?.complete(continuousTranscript.toString())
+ if (!isContinuousListening) {
+ // Fix race: if stop was called between cycles, complete the gate now
+ listenGate?.complete(buildFinalTranscript())
+ return
+ }
+ currentPartialResult = "" // Reset for new segment
+ var recognizer = currentRecognizer
+ if (recognizer == null) {
+ val newRec = SpeechRecognizer.createSpeechRecognizer(context)
+ currentRecognizer = newRec
+ recognizer = newRec
+ newRec.setRecognitionListener(object : RecognitionListener {
+ override fun onReadyForSpeech(params: Bundle?) {
+ Log.d(TAG, "onReadyForSpeech")
}
- }
- override fun onResults(results: Bundle?) {
- val matches = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
- val text = matches?.firstOrNull() ?: ""
- if (text.isNotBlank()) {
- if (continuousTranscript.isNotEmpty()) continuousTranscript.append(" ")
- continuousTranscript.append(text)
+ override fun onBeginningOfSpeech() { Log.d(TAG, "onBeginningOfSpeech") }
+ override fun onRmsChanged(rmsdB: Float) {}
+ override fun onBufferReceived(buffer: ByteArray?) {}
+ override fun onEndOfSpeech() { Log.d(TAG, "onEndOfSpeech") }
+ override fun onError(error: Int) {
+ Log.d(TAG, "onError: $error")
+ if (error == SpeechRecognizer.ERROR_CLIENT ||
+ error == SpeechRecognizer.ERROR_RECOGNIZER_BUSY ||
+ error == SpeechRecognizer.ERROR_SERVER
+ ) {
+ try {
+ currentRecognizer?.destroy()
+ } catch (_: Exception) {}
+ currentRecognizer = null
+ }
+ if (isContinuousListening) {
+ mainHandler.post { startContinuousListeningCycle() }
+ } else {
+ unmuteBeep()
+ listenGate?.complete(buildFinalTranscript())
+ }
}
- currentRecognizer?.destroy()
- currentRecognizer = null
- if (isContinuousListening) {
- mainHandler.post { startContinuousListeningCycle() }
- } else {
- listenGate?.complete(continuousTranscript.toString())
+ override fun onResults(results: Bundle?) {
+ Log.d(TAG, "onResults")
+ val matches = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
+ val text = matches?.firstOrNull() ?: ""
+ if (text.isNotBlank()) {
+ if (continuousTranscript.isNotEmpty()) continuousTranscript.append(" ")
+ continuousTranscript.append(text)
+ }
+ currentPartialResult = "" // Final result supersedes partial
+ if (isContinuousListening) {
+ mainHandler.post { startContinuousListeningCycle() }
+ } else {
+ unmuteBeep()
+ listenGate?.complete(buildFinalTranscript())
+ }
}
- }
- override fun onPartialResults(partialResults: Bundle?) {}
- override fun onEvent(eventType: Int, params: Bundle?) {}
- })
+ override fun onPartialResults(partialResults: Bundle?) {
+ Log.d(TAG, "onPartialResults")
+ val matches = partialResults?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
+ val text = matches?.firstOrNull() ?: ""
+ if (text.isNotBlank()) {
+ currentPartialResult = text
+ }
+ }
+ override fun onEvent(eventType: Int, params: Bundle?) { Log.d(TAG, "onEvent: $eventType") }
+
+ override fun onSegmentResults(segmentResults: Bundle) {
+ Log.d(TAG, "onSegmentResults")
+ val matches = segmentResults.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
+ val text = matches?.firstOrNull() ?: ""
+ if (text.isNotBlank()) {
+ if (continuousTranscript.isNotEmpty()) continuousTranscript.append(" ")
+ continuousTranscript.append(text)
+ }
+ currentPartialResult = ""
+ }
+
+ override fun onEndOfSegmentedSession() {
+ Log.d(TAG, "onEndOfSegmentedSession")
+ if (isContinuousListening) {
+ mainHandler.post { startContinuousListeningCycle() }
+ } else {
+ unmuteBeep()
+ listenGate?.complete(buildFinalTranscript())
+ }
+ }
+ })
+ }
val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
putExtra(RecognizerIntent.EXTRA_LANGUAGE, java.util.Locale.getDefault())
+ putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true)
// Prevent auto-stopping on pauses to mimic API-based continuous recording
- putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS, 100000L)
- putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS, 100000L)
- putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS, 100000L)
+ putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS, 20000L)
+ putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS, 20000L)
+ putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS, 20000L)
+ putExtra("android.speech.extra.DICTATION_MODE", true)
+ if (android.os.Build.VERSION.SDK_INT >= 33) {
+ putExtra(
+ RecognizerIntent.EXTRA_SEGMENTED_SESSION,
+ RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS
+ )
+ }
}
try {
- recognizer.startListening(intent)
+ muteBeep()
+ recognizer?.startListening(intent)
} catch (_: Exception) {
+ unmuteBeep()
isContinuousListening = false
- listenGate?.complete(continuousTranscript.toString())
+ listenGate?.complete(buildFinalTranscript())
}
}
/** Stop Android SpeechRecognizer and return the recognized text. */
suspend fun stopAndroidListening(): String {
isContinuousListening = false
- currentRecognizer?.stopListening()
- // The stopListening() call triggers onResults which completes the gate
- val result = listenGate?.await() ?: continuousTranscript.toString()
+ val rec = currentRecognizer
+ if (rec != null) {
+ rec.stopListening()
+ // Wait for onResults to fire and complete the gate, with a timeout
+ // to avoid hanging if the recognizer is unresponsive or between cycles.
+ val gateResult = kotlinx.coroutines.withTimeoutOrNull(3000L) {
+ listenGate?.await()
+ }
+ if (gateResult != null) {
+ unmuteBeep()
+ listenGate = null
+ return gateResult
+ }
+ // Timed out — force cleanup
+ mainHandler.post {
+ unmuteBeep()
+ currentRecognizer?.cancel()
+ currentRecognizer?.destroy()
+ currentRecognizer = null
+ }
+ }
+ // Recognizer was null (between cycles) or timed out — return what we have
+ val result = buildFinalTranscript()
+ unmuteBeep()
+ listenGate?.complete(result)
listenGate = null
return result
}
+ /**
+ * Build the final transcript by appending the current in-flight partial
+ * result (if any) to the accumulated finalized segments.
+ */
+ private fun buildFinalTranscript(): String {
+ val base = continuousTranscript.toString()
+ val partial = currentPartialResult
+ currentPartialResult = ""
+ if (partial.isBlank()) return base
+ return if (base.isNotBlank()) "$base $partial" else partial
+ }
+
/**
* Listen for a single utterance hands-free: the recognizer endpoints on
* its own (no stop call needed) and this returns the transcript or the
@@ -202,6 +306,7 @@ class SttEngine(
// SpeechRecognizer must be created and driven from the main thread.
withContext(Dispatchers.Main) {
try {
+ muteBeep()
val recognizer = SpeechRecognizer.createSpeechRecognizer(context)
currentRecognizer = recognizer
recognizer.setRecognitionListener(object : RecognitionListener {
@@ -211,11 +316,13 @@ class SttEngine(
override fun onBufferReceived(buffer: ByteArray?) {}
override fun onEndOfSpeech() {}
override fun onError(error: Int) {
+ unmuteBeep()
gate.complete(SttOutcome.Error(error))
currentRecognizer?.destroy()
currentRecognizer = null
}
override fun onResults(results: Bundle?) {
+ unmuteBeep()
val matches = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
gate.complete(SttOutcome.Text(matches?.firstOrNull() ?: ""))
currentRecognizer?.destroy()
@@ -223,6 +330,8 @@ class SttEngine(
}
override fun onPartialResults(partialResults: Bundle?) {}
override fun onEvent(eventType: Int, params: Bundle?) {}
+ override fun onSegmentResults(segmentResults: Bundle) {}
+ override fun onEndOfSegmentedSession() {}
})
val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
@@ -230,6 +339,7 @@ class SttEngine(
}
recognizer.startListening(intent)
} catch (_: Exception) {
+ unmuteBeep()
gate.complete(SttOutcome.Error(SpeechRecognizer.ERROR_CLIENT))
currentRecognizer = null
}
@@ -286,10 +396,12 @@ class SttEngine(
when (provider) {
AudioProvider.ANDROID -> {
isContinuousListening = false
+ currentPartialResult = ""
onceGate?.complete(SttOutcome.Error(ERROR_CANCELLED))
listenGate?.complete("")
listenGate = null
mainHandler.post {
+ unmuteBeep()
try {
currentRecognizer?.cancel()
currentRecognizer?.destroy()
@@ -311,7 +423,33 @@ class SttEngine(
}
}
+ private fun muteBeep() {
+ if (!isMutedForRestart) {
+ try {
+ audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_MUTE, 0)
+ audioManager.adjustStreamVolume(AudioManager.STREAM_SYSTEM, AudioManager.ADJUST_MUTE, 0)
+ audioManager.adjustStreamVolume(AudioManager.STREAM_NOTIFICATION, AudioManager.ADJUST_MUTE, 0)
+ audioManager.adjustStreamVolume(AudioManager.STREAM_RING, AudioManager.ADJUST_MUTE, 0)
+ } catch (_: Exception) {}
+ isMutedForRestart = true
+ }
+ }
+
+ private fun unmuteBeep() {
+ if (isMutedForRestart) {
+ try {
+ audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_UNMUTE, 0)
+ audioManager.adjustStreamVolume(AudioManager.STREAM_SYSTEM, AudioManager.ADJUST_UNMUTE, 0)
+ audioManager.adjustStreamVolume(AudioManager.STREAM_NOTIFICATION, AudioManager.ADJUST_UNMUTE, 0)
+ audioManager.adjustStreamVolume(AudioManager.STREAM_RING, AudioManager.ADJUST_UNMUTE, 0)
+ } catch (_: Exception) {}
+ isMutedForRestart = false
+ }
+ }
+
companion object {
+ private const val TAG = "SttEngine"
+
/** Synthetic error code: listening was cancelled by pause/end, not by the recognizer. */
const val ERROR_CANCELLED = -100
}
diff --git a/test_speech2.kt b/test_speech2.kt
new file mode 100644
index 0000000..f93cac5
--- /dev/null
+++ b/test_speech2.kt
@@ -0,0 +1,3 @@
+import android.speech.RecognizerIntent
+
+fun main() {}
diff --git a/test_speech3.kt b/test_speech3.kt
new file mode 100644
index 0000000..f93cac5
--- /dev/null
+++ b/test_speech3.kt
@@ -0,0 +1,3 @@
+import android.speech.RecognizerIntent
+
+fun main() {}
diff --git a/test_speech4.kt b/test_speech4.kt
new file mode 100644
index 0000000..2db874c
--- /dev/null
+++ b/test_speech4.kt
@@ -0,0 +1,5 @@
+import android.speech.RecognizerIntent
+
+fun main() {
+ println(RecognizerIntent.EXTRA_SEGMENTED_SESSION)
+}
diff --git a/test_speech5.kt b/test_speech5.kt
new file mode 100644
index 0000000..fbe4625
--- /dev/null
+++ b/test_speech5.kt
@@ -0,0 +1,6 @@
+import android.speech.RecognizerIntent
+
+fun main() {
+ println(RecognizerIntent.EXTRA_SEGMENTED_SESSION)
+ // println(RecognizerIntent.EXTRA_SEGMENTED_SESSION_DICTATION) // If this exists
+}