Skip to content

Commit 52bce84

Browse files
authored
fix(android): stop interrupted assistant audio and remove cached files (#129574)
1 parent 8d05d6c commit 52bce84

2 files changed

Lines changed: 224 additions & 43 deletions

File tree

‎apps/android/app/src/main/java/ai/openclaw/app/voice/TalkAudioPlayer.kt‎

Lines changed: 53 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import android.media.MediaPlayer
88
import kotlinx.coroutines.CancellationException
99
import kotlinx.coroutines.CompletableDeferred
1010
import kotlinx.coroutines.Dispatchers
11+
import kotlinx.coroutines.NonCancellable
1112
import kotlinx.coroutines.delay
1213
import kotlinx.coroutines.withContext
1314
import java.io.File
@@ -180,58 +181,67 @@ internal class TalkAudioPlayer(
180181
) {
181182
// MediaPlayer needs a seekable data source for several compressed formats,
182183
// so cache the response bytes briefly instead of streaming from memory.
183-
val tempFile =
184-
withContext(Dispatchers.IO) {
185-
File.createTempFile("talk-audio-", fileExtension, context.cacheDir).apply {
186-
writeBytes(bytes)
187-
}
188-
}
184+
// Own resources immediately: cancellation can discard a dispatcher result after allocation.
185+
var tempFile: File? = null
189186
try {
190-
val finished = CompletableDeferred<Unit>()
191-
val player =
192-
withContext(Dispatchers.Main) {
193-
MediaPlayer().apply {
194-
setAudioAttributes(
195-
AudioAttributes
196-
.Builder()
197-
.setUsage(AudioAttributes.USAGE_MEDIA)
198-
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
199-
.build(),
200-
)
201-
setDataSource(tempFile.absolutePath)
202-
setOnCompletionListener {
203-
finished.complete(Unit)
204-
}
205-
setOnErrorListener { _, what, extra ->
206-
finished.completeExceptionally(IllegalStateException("MediaPlayer error ($what/$extra)"))
207-
true
208-
}
209-
prepare()
187+
val audioFile =
188+
withContext(Dispatchers.IO) {
189+
File.createTempFile("talk-audio-", fileExtension, context.cacheDir).also { created ->
190+
tempFile = created
191+
created.writeBytes(bytes)
210192
}
211193
}
212-
val playback =
213-
ActivePlayback(
214-
cancel = {
215-
finished.completeExceptionally(CancellationException("assistant speech cancelled"))
216-
runCatching { player.stop() }
217-
},
218-
)
219-
register(playback)
194+
val finished = CompletableDeferred<Unit>()
195+
var mediaPlayer: MediaPlayer? = null
220196
try {
221-
withContext(Dispatchers.Main) {
222-
player.start()
197+
val player =
198+
withContext(Dispatchers.Main) {
199+
MediaPlayer().also { mediaPlayer = it }.apply {
200+
setAudioAttributes(
201+
AudioAttributes
202+
.Builder()
203+
.setUsage(AudioAttributes.USAGE_MEDIA)
204+
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
205+
.build(),
206+
)
207+
setDataSource(audioFile.absolutePath)
208+
setOnCompletionListener {
209+
finished.complete(Unit)
210+
}
211+
setOnErrorListener { _, what, extra ->
212+
finished.completeExceptionally(IllegalStateException("MediaPlayer error ($what/$extra)"))
213+
true
214+
}
215+
prepare()
216+
}
217+
}
218+
val playback =
219+
ActivePlayback(
220+
cancel = {
221+
finished.completeExceptionally(CancellationException("assistant speech cancelled"))
222+
runCatching { player.stop() }
223+
},
224+
)
225+
register(playback)
226+
try {
227+
withContext(Dispatchers.Main) {
228+
player.start()
229+
}
230+
finished.await()
231+
} finally {
232+
clear(playback)
223233
}
224-
finished.await()
225234
} finally {
226-
clear(playback)
227-
withContext(Dispatchers.Main) {
228-
runCatching { player.stop() }
229-
player.release()
235+
withContext(NonCancellable + Dispatchers.Main) {
236+
mediaPlayer?.let { player ->
237+
runCatching { player.stop() }
238+
player.release()
239+
}
230240
}
231241
}
232242
} finally {
233-
withContext(Dispatchers.IO) {
234-
tempFile.delete()
243+
withContext(NonCancellable + Dispatchers.IO) {
244+
tempFile?.delete()
235245
}
236246
}
237247
}

‎apps/android/app/src/test/java/ai/openclaw/app/voice/TalkAudioPlayerTest.kt‎

Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,52 @@
11
package ai.openclaw.app.voice
22

3+
import android.media.MediaPlayer
4+
import kotlinx.coroutines.CoroutineScope
5+
import kotlinx.coroutines.Dispatchers
6+
import kotlinx.coroutines.ExperimentalCoroutinesApi
7+
import kotlinx.coroutines.asCoroutineDispatcher
8+
import kotlinx.coroutines.cancel
9+
import kotlinx.coroutines.cancelAndJoin
10+
import kotlinx.coroutines.delay
11+
import kotlinx.coroutines.launch
12+
import kotlinx.coroutines.runBlocking
13+
import kotlinx.coroutines.test.resetMain
14+
import kotlinx.coroutines.test.setMain
15+
import kotlinx.coroutines.withTimeout
16+
import org.junit.After
317
import org.junit.Assert.assertEquals
418
import org.junit.Assert.assertTrue
19+
import org.junit.Before
520
import org.junit.Test
21+
import org.junit.runner.RunWith
22+
import org.robolectric.RobolectricTestRunner
23+
import org.robolectric.RuntimeEnvironment
24+
import org.robolectric.annotation.Config
25+
import org.robolectric.shadows.ShadowMediaPlayer
26+
import java.io.File
27+
import java.util.concurrent.CountDownLatch
28+
import java.util.concurrent.Executors
29+
import java.util.concurrent.atomic.AtomicReference
630

31+
@RunWith(RobolectricTestRunner::class)
32+
@Config(sdk = [34])
33+
@OptIn(ExperimentalCoroutinesApi::class)
734
class TalkAudioPlayerTest {
35+
private val context = RuntimeEnvironment.getApplication()
36+
37+
@Before
38+
fun setUpPlayback() {
39+
Dispatchers.setMain(Dispatchers.Unconfined)
40+
ShadowMediaPlayer.setMediaInfoProvider { ShadowMediaPlayer.MediaInfo(60_000, 0) }
41+
}
42+
43+
@After
44+
fun cleanUpPlayback() {
45+
speechFiles().forEach(File::delete)
46+
ShadowMediaPlayer.resetStaticState()
47+
Dispatchers.resetMain()
48+
}
49+
850
@Test
951
fun resolvesPcmPlaybackFromOutputFormat() {
1052
val mode =
@@ -41,4 +83,133 @@ class TalkAudioPlayerTest {
4183
assertTrue(mode is TalkPlaybackMode.Compressed)
4284
assertEquals(".webm", (mode as TalkPlaybackMode.Compressed).fileExtension)
4385
}
86+
87+
@Test
88+
fun cancelledCompressedPlaybackReleasesMediaPlayer() {
89+
val outcome = cancelCompressedPlayback()
90+
91+
assertEquals(ShadowMediaPlayer.State.END, outcome.playerState)
92+
}
93+
94+
@Test
95+
fun cancelledCompressedPlaybackDeletesPrivateSpeechFile() {
96+
val outcome = cancelCompressedPlayback()
97+
98+
assertEquals(emptyList<String>(), outcome.remainingSpeechFiles)
99+
}
100+
101+
@Test
102+
fun compressedPlaybackSetupFailureReleasesAllocatedMediaPlayer() =
103+
runBlocking {
104+
val createdPlayer = AtomicReference<MediaPlayer>()
105+
val createdShadow = AtomicReference<ShadowMediaPlayer>()
106+
ShadowMediaPlayer.setCreateListener { player, shadow ->
107+
createdPlayer.set(player)
108+
createdShadow.set(shadow)
109+
}
110+
ShadowMediaPlayer.setMediaInfoProvider { throw IllegalStateException("synthetic media initialization failed") }
111+
112+
try {
113+
val failure = runCatching { TalkAudioPlayer(context).play(syntheticAudio()) }.exceptionOrNull()
114+
115+
assertEquals("synthetic media initialization failed", failure?.message)
116+
assertEquals(ShadowMediaPlayer.State.END, checkNotNull(createdShadow.get()).state)
117+
assertEquals(emptyList<String>(), speechFiles().map(File::getName))
118+
} finally {
119+
runCatching { createdPlayer.get()?.release() }
120+
speechFiles().forEach(File::delete)
121+
}
122+
}
123+
124+
@Test
125+
fun cancellationBeforeCreatedFileReturnsDeletesPrivateSpeechFile() =
126+
runBlocking {
127+
val dispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
128+
val blockerScope = CoroutineScope(dispatcher)
129+
val callerBlocked = CountDownLatch(1)
130+
val releaseCaller = CountDownLatch(1)
131+
val player = TalkAudioPlayer(context)
132+
val playback =
133+
launch(dispatcher) {
134+
blockerScope.launch {
135+
callerBlocked.countDown()
136+
releaseCaller.await()
137+
}
138+
player.play(syntheticAudio())
139+
}
140+
141+
try {
142+
withTimeout(5_000) {
143+
while (callerBlocked.count > 0 || speechFiles().isEmpty()) {
144+
delay(10)
145+
}
146+
}
147+
assertEquals(1, speechFiles().size)
148+
149+
playback.cancel()
150+
releaseCaller.countDown()
151+
playback.join()
152+
153+
assertEquals(emptyList<String>(), speechFiles().map(File::getName))
154+
} finally {
155+
releaseCaller.countDown()
156+
playback.cancelAndJoin()
157+
blockerScope.cancel()
158+
dispatcher.close()
159+
speechFiles().forEach(File::delete)
160+
}
161+
}
162+
163+
private fun cancelCompressedPlayback(): CancelledPlaybackOutcome =
164+
runBlocking {
165+
val createdPlayer = AtomicReference<MediaPlayer>()
166+
val createdShadow = AtomicReference<ShadowMediaPlayer>()
167+
ShadowMediaPlayer.setCreateListener { player, shadow ->
168+
createdPlayer.set(player)
169+
createdShadow.set(shadow)
170+
}
171+
val player = TalkAudioPlayer(context)
172+
val playback = launch(Dispatchers.Default) { player.play(syntheticAudio()) }
173+
174+
try {
175+
withTimeout(5_000) {
176+
while (createdShadow.get()?.state != ShadowMediaPlayer.State.STARTED) {
177+
delay(10)
178+
}
179+
}
180+
val activeFiles = speechFiles()
181+
assertEquals(1, activeFiles.size)
182+
183+
playback.cancelAndJoin()
184+
185+
CancelledPlaybackOutcome(
186+
playerState = checkNotNull(createdShadow.get()).state,
187+
remainingSpeechFiles = speechFiles().map(File::getName),
188+
)
189+
} finally {
190+
playback.cancelAndJoin()
191+
runCatching { createdPlayer.get()?.release() }
192+
speechFiles().forEach(File::delete)
193+
}
194+
}
195+
196+
private fun speechFiles(): List<File> {
197+
val files = context.cacheDir.listFiles().orEmpty()
198+
return files.filter { it.name.startsWith("talk-audio-") }
199+
}
200+
201+
private fun syntheticAudio(): TalkSpeakAudio =
202+
TalkSpeakAudio(
203+
bytes = byteArrayOf(1, 2, 3),
204+
provider = "test",
205+
outputFormat = null,
206+
voiceCompatible = null,
207+
mimeType = "audio/mpeg",
208+
fileExtension = null,
209+
)
210+
211+
private data class CancelledPlaybackOutcome(
212+
val playerState: ShadowMediaPlayer.State,
213+
val remainingSpeechFiles: List<String>,
214+
)
44215
}

0 commit comments

Comments
 (0)