11package ai.openclaw.app.chat
22
33import ai.openclaw.app.gateway.GatewaySession
4+ import ai.openclaw.app.voice.LocalSpeechSpeaking
45import ai.openclaw.app.voice.TalkAudioPlaying
56import ai.openclaw.app.voice.TalkSpeakAudio
6- import android.content.Context
7- import android.speech.tts.TextToSpeech
8- import android.speech.tts.UtteranceProgressListener
97import android.util.Log
108import kotlinx.coroutines.CancellationException
11- import kotlinx.coroutines.CompletableDeferred
129import kotlinx.coroutines.CoroutineScope
13- import kotlinx.coroutines.Dispatchers
1410import kotlinx.coroutines.Job
15- import kotlinx.coroutines.NonCancellable
1611import kotlinx.coroutines.flow.MutableStateFlow
1712import kotlinx.coroutines.flow.StateFlow
1813import kotlinx.coroutines.flow.asStateFlow
1914import kotlinx.coroutines.launch
20- import kotlinx.coroutines.withContext
2115import kotlinx.serialization.Serializable
2216import kotlinx.serialization.encodeToString
2317import kotlinx.serialization.json.Json
@@ -28,26 +22,23 @@ private const val TAG = "MessageSpeech"
2822internal enum class MessageSpeechPhase {
2923 Preparing ,
3024 Speaking ,
25+ Failed ,
3126}
3227
33- /* * Playback state for the chat Listen action; null when idle . */
28+ /* * Listen state; a failed request remains retryable without claiming audio or microphone use . */
3429internal data class MessageSpeechState (
3530 val messageId : String ,
3631 val phase : MessageSpeechPhase ,
37- )
32+ ) {
33+ val isActive: Boolean
34+ get() = phase != MessageSpeechPhase .Failed
35+ }
3836
3937/* * Renders message text to an audio clip; null means fall back to local TTS. */
4038internal fun interface MessageSpeechSynthesizing {
4139 suspend fun synthesize (text : String ): TalkSpeakAudio ?
4240}
4341
44- /* * Speaks text with the on-device engine when the gateway cannot render audio. */
45- internal interface LocalSpeechSpeaking {
46- suspend fun speak (text : String )
47-
48- fun stop ()
49- }
50-
5142/* * Gateway tts.speak client using the general configured TTS provider chain. */
5243internal class MessageSpeechClient (
5344 private val session : GatewaySession ? = null ,
@@ -141,7 +132,7 @@ internal class MessageSpeechController(
141132 messageId : String ,
142133 text : String ,
143134 ) {
144- if (_state .value?.messageId == messageId) {
135+ if (_state .value?.let { it. messageId == messageId && it.isActive } == true ) {
145136 stop()
146137 return
147138 }
@@ -175,8 +166,13 @@ internal class MessageSpeechController(
175166 if (! playClip(clip) && generation.get() == token) {
176167 localSpeech.speak(spoken)
177168 }
169+ } catch (err: CancellationException ) {
170+ throw err
171+ } catch (err: Throwable ) {
172+ Log .w(TAG , " local speech failed: ${err.message ? : err::class .simpleName} " )
173+ if (generation.get() == token) _state .value = MessageSpeechState (messageId, MessageSpeechPhase .Failed )
178174 } finally {
179- if (generation.get() == token) _state .value = null
175+ if (generation.get() == token && _state .value?.isActive == true ) _state .value = null
180176 }
181177 }
182178 }
@@ -194,110 +190,3 @@ internal class MessageSpeechController(
194190 }
195191 }
196192}
197-
198- /* * Minimal on-device TTS wrapper for the chat Listen fallback voice. */
199- internal class SystemSpeechSpeaker (
200- private val context : Context ,
201- ) : LocalSpeechSpeaking {
202- private val lock = Any ()
203- private var engine: TextToSpeech ? = null
204- private var ready: CompletableDeferred <Boolean >? = null
205- private var active: CompletableDeferred <Unit >? = null
206-
207- override suspend fun speak (text : String ) {
208- val engine = ensureEngine() ? : return
209- val utteranceId = " chat-listen-${System .nanoTime()} "
210- val done = CompletableDeferred <Unit >()
211- synchronized(lock) {
212- active?.cancel()
213- active = done
214- }
215- withContext(Dispatchers .Main .immediate) {
216- engine.setOnUtteranceProgressListener(
217- object : UtteranceProgressListener () {
218- override fun onStart (id : String? ) {}
219-
220- override fun onDone (id : String? ) {
221- if (id == utteranceId) done.complete(Unit )
222- }
223-
224- @Deprecated(" Deprecated in Java" )
225- override fun onError (id : String? ) {
226- if (id == utteranceId) done.complete(Unit )
227- }
228-
229- override fun onError (
230- id : String? ,
231- errorCode : Int ,
232- ) {
233- if (id == utteranceId) done.complete(Unit )
234- }
235- },
236- )
237- if (engine.speak(text, TextToSpeech .QUEUE_FLUSH , null , utteranceId) != TextToSpeech .SUCCESS ) {
238- done.complete(Unit )
239- }
240- }
241- try {
242- done.await()
243- } finally {
244- synchronized(lock) {
245- if (active == = done) active = null
246- }
247- }
248- }
249-
250- override fun stop () {
251- synchronized(lock) {
252- active?.cancel()
253- active = null
254- }
255- engine?.stop()
256- }
257-
258- private suspend fun ensureEngine (): TextToSpeech ? {
259- val current = synchronized(lock) { ready }
260- val pending = current ? : createEngine()
261- if (pending.await()) return synchronized(lock) { engine }
262-
263- // A failed Android TTS service can recover later; do not cache its failed initialization.
264- val failedEngine =
265- synchronized(lock) {
266- if (ready != = pending) return null
267- ready = null
268- engine.also { engine = null }
269- }
270- withContext(Dispatchers .Main .immediate) { failedEngine?.shutdown() }
271- return null
272- }
273-
274- private suspend fun createEngine (): CompletableDeferred <Boolean > {
275- val pending = CompletableDeferred <Boolean >()
276- val ownsInitialization =
277- synchronized(lock) {
278- if (ready != null ) {
279- false
280- } else {
281- ready = pending
282- true
283- }
284- }
285- if (! ownsInitialization) return synchronized(lock) { checkNotNull(ready) }
286-
287- val created =
288- try {
289- // Finish publishing the constructed engine even if the Listen job is stopped mid-init.
290- withContext(NonCancellable + Dispatchers .Main .immediate) {
291- TextToSpeech (context) { status -> pending.complete(status == TextToSpeech .SUCCESS ) }
292- }
293- } catch (err: Throwable ) {
294- Log .d(TAG , " system TTS initialization failed: ${err.message ? : err::class .simpleName} " )
295- pending.complete(false )
296- null
297- }
298- synchronized(lock) {
299- if (ready == = pending) engine = created else created?.shutdown()
300- }
301- return pending
302- }
303- }
0 commit comments