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: hands-free STT turn + fully suspending TTS playback

Durganshu Mishraa229477ceb62
diff --git a/app/src/main/java/com/gotcha/audio/SttEngine.kt b/app/src/main/java/com/gotcha/audio/SttEngine.kt
index 17f856f..06fbdaf 100644
--- a/app/src/main/java/com/gotcha/audio/SttEngine.kt
+++ b/app/src/main/java/com/gotcha/audio/SttEngine.kt
@@ -4,6 +4,8 @@ import android.content.Context
import android.content.Intent
import android.media.MediaRecorder
import android.os.Bundle
+import android.os.Handler
+import android.os.Looper
import android.speech.RecognitionListener
import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
@@ -12,6 +14,17 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
+/** Result of a single hands-free listening turn ([SttEngine.listenOnceAndroid]). */
+sealed class SttOutcome {
+ data class Text(val text: String) : SttOutcome()
+ data class Error(val code: Int) : SttOutcome() {
+ /** True for silence/no-speech errors that a continuous loop should just retry. */
+ val isBenign: Boolean
+ get() = code == SpeechRecognizer.ERROR_NO_MATCH ||
+ code == SpeechRecognizer.ERROR_SPEECH_TIMEOUT
+ }
+}
+
/**
* Speech-to-Text engine supporting two providers.
* Both use a push-to-talk pattern: startRecording() / stopRecording().
@@ -30,8 +43,10 @@ class SttEngine(
private var currentAudioFile: File? = null
// Android STT state
+ private val mainHandler = Handler(Looper.getMainLooper())
private var currentRecognizer: SpeechRecognizer? = null
private var listenGate: CompletableDeferred<String>? = null
+ private var onceGate: CompletableDeferred<SttOutcome>? = null
/** The models available from the API (empty if provider is Android). */
var apiSttModels: List<AudioModel> = emptyList()
@@ -137,4 +152,77 @@ class SttEngine(
listenGate = null
return result
}
+
+ /**
+ * Listen for a single utterance hands-free: the recognizer endpoints on
+ * its own (no stop call needed) and this returns the transcript or the
+ * SpeechRecognizer error code. Used by the voice-call loop.
+ */
+ suspend fun listenOnceAndroid(): SttOutcome {
+ if (currentRecognizer != null || onceGate != null) {
+ return SttOutcome.Error(SpeechRecognizer.ERROR_RECOGNIZER_BUSY)
+ }
+ val gate = CompletableDeferred<SttOutcome>()
+ onceGate = gate
+ // SpeechRecognizer must be created and driven from the main thread.
+ withContext(Dispatchers.Main) {
+ try {
+ 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) {
+ gate.complete(SttOutcome.Error(error))
+ currentRecognizer?.destroy()
+ currentRecognizer = null
+ }
+ override fun onResults(results: Bundle?) {
+ val matches = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
+ gate.complete(SttOutcome.Text(matches?.firstOrNull() ?: ""))
+ currentRecognizer?.destroy()
+ currentRecognizer = null
+ }
+ override fun onPartialResults(partialResults: Bundle?) {}
+ override fun onEvent(eventType: Int, params: Bundle?) {}
+ })
+ 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())
+ }
+ recognizer.startListening(intent)
+ } catch (_: Exception) {
+ gate.complete(SttOutcome.Error(SpeechRecognizer.ERROR_CLIENT))
+ currentRecognizer = null
+ }
+ }
+ return try {
+ gate.await()
+ } finally {
+ onceGate = null
+ }
+ }
+
+ /**
+ * Abort an in-flight [listenOnceAndroid] (pause/end of a call). Safe to
+ * call from any thread; a suspended caller unblocks with [ERROR_CANCELLED].
+ */
+ fun cancelListening() {
+ onceGate?.complete(SttOutcome.Error(ERROR_CANCELLED))
+ mainHandler.post {
+ try {
+ currentRecognizer?.cancel()
+ currentRecognizer?.destroy()
+ } catch (_: Exception) { }
+ currentRecognizer = null
+ }
+ }
+
+ companion object {
+ /** Synthetic error code: listening was cancelled by pause/end, not by the recognizer. */
+ const val ERROR_CANCELLED = -100
+ }
}
diff --git a/app/src/main/java/com/gotcha/audio/TtsEngine.kt b/app/src/main/java/com/gotcha/audio/TtsEngine.kt
index 373980a..5c2613b 100644
--- a/app/src/main/java/com/gotcha/audio/TtsEngine.kt
+++ b/app/src/main/java/com/gotcha/audio/TtsEngine.kt
@@ -9,6 +9,7 @@ import android.speech.tts.UtteranceProgressListener
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
+import kotlinx.coroutines.withTimeoutOrNull
import java.util.Locale
/**
@@ -26,6 +27,12 @@ class TtsEngine(
private var androidReady = false
private var ttsInitGate = CompletableDeferred<Boolean>()
+ @Volatile
+ private var currentTrack: AudioTrack? = null
+
+ @Volatile
+ private var playbackGate: CompletableDeferred<Unit>? = null
+
/** The models available from the API (empty if provider is Android). */
var apiTtsModels: List<AudioModel> = emptyList()
private set
@@ -85,6 +92,9 @@ class TtsEngine(
override fun onStart(utteranceId: String?) {}
override fun onDone(utteranceId: String?) { gate.complete(true) }
override fun onError(utteranceId: String?) { gate.complete(false) }
+ // stop() interrupts the utterance; without this the gate never completes
+ // and a suspended speak() would hang (e.g. pausing a voice call).
+ override fun onStop(utteranceId: String?, interrupted: Boolean) { gate.complete(false) }
})
tts.setLanguage(Locale.US)
val result = tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, "tts_utterance")
@@ -100,8 +110,12 @@ class TtsEngine(
return playPcmAudio(audioBytes)
}
- /** Play raw PCM/WAV audio bytes through AudioTrack. */
- private fun playPcmAudio(bytes: ByteArray): Boolean {
+ /**
+ * Play raw PCM/WAV audio bytes through AudioTrack, suspending until
+ * playback completes (or [stop] interrupts it) so callers can sequence
+ * speech with other audio work (e.g. re-arming the mic in a voice call).
+ */
+ private suspend fun playPcmAudio(bytes: ByteArray): Boolean {
return try {
// If it's a WAV file, skip the 44-byte header
val pcmData = if (bytes.size > 44 &&
@@ -123,28 +137,64 @@ class TtsEngine(
.setAudioFormat(
AudioFormat.Builder()
.setEncoding(AudioFormat.ENCODING_PCM_16BIT)
- .setSampleRate(24000)
+ .setSampleRate(SAMPLE_RATE_HZ)
.setChannelMask(AudioFormat.CHANNEL_OUT_MONO)
.build()
)
.setBufferSizeInBytes(pcmData.size)
.setTransferMode(AudioTrack.MODE_STATIC)
.build()
+
+ val done = CompletableDeferred<Unit>()
+ currentTrack = track
+ playbackGate = done
+ // Marker position is in frames: 16-bit mono = 2 bytes per frame.
+ track.setNotificationMarkerPosition(pcmData.size / 2)
+ track.setPlaybackPositionUpdateListener(object : AudioTrack.OnPlaybackPositionUpdateListener {
+ override fun onMarkerReached(t: AudioTrack?) { done.complete(Unit) }
+ override fun onPeriodicNotification(t: AudioTrack?) {}
+ })
track.write(pcmData, 0, pcmData.size)
track.play()
+ // Fallback in case the marker callback never fires on some devices.
+ val durationMs = pcmData.size / 2 * 1000L / SAMPLE_RATE_HZ
+ withTimeoutOrNull(durationMs + PLAYBACK_TIMEOUT_SLACK_MS) { done.await() }
+ releaseTrack()
true
- } catch (_: Exception) { false }
+ } catch (_: Exception) {
+ releaseTrack()
+ false
+ }
}
- /** Stop any ongoing speech. */
+ private fun releaseTrack() {
+ try {
+ currentTrack?.release()
+ } catch (_: Exception) { }
+ currentTrack = null
+ playbackGate = null
+ }
+
+ /** Stop any ongoing speech (both providers). Unblocks a suspended [speak]. */
fun stop() {
androidTts?.stop()
+ try {
+ currentTrack?.pause()
+ currentTrack?.flush()
+ } catch (_: Exception) { }
+ playbackGate?.complete(Unit)
}
/** Release resources. */
fun shutdown() {
- androidTts?.stop()
+ stop()
+ releaseTrack()
androidTts?.shutdown()
androidTts = null
}
+
+ private companion object {
+ const val SAMPLE_RATE_HZ = 24000
+ const val PLAYBACK_TIMEOUT_SLACK_MS = 500L
+ }
}