@@ -165,44 +165,49 @@ internal class TalkAudioPlayer(
165165 writeBytes(bytes)
166166 }
167167 }
168- val finished = CompletableDeferred <Unit >()
169- val player =
170- withContext(Dispatchers .Main ) {
171- MediaPlayer ().apply {
172- setAudioAttributes(
173- AudioAttributes .Builder ()
174- .setUsage(AudioAttributes .USAGE_MEDIA )
175- .setContentType(AudioAttributes .CONTENT_TYPE_SPEECH )
176- .build(),
177- )
178- setDataSource(tempFile.absolutePath)
179- setOnCompletionListener {
180- finished.complete(Unit )
181- }
182- setOnErrorListener { _, what, extra ->
183- finished.completeExceptionally(IllegalStateException (" MediaPlayer error ($what /$extra )" ))
184- true
168+ try {
169+ val finished = CompletableDeferred <Unit >()
170+ val player =
171+ withContext(Dispatchers .Main ) {
172+ MediaPlayer ().apply {
173+ setAudioAttributes(
174+ AudioAttributes .Builder ()
175+ .setUsage(AudioAttributes .USAGE_MEDIA )
176+ .setContentType(AudioAttributes .CONTENT_TYPE_SPEECH )
177+ .build(),
178+ )
179+ setDataSource(tempFile.absolutePath)
180+ setOnCompletionListener {
181+ finished.complete(Unit )
182+ }
183+ setOnErrorListener { _, what, extra ->
184+ finished.completeExceptionally(IllegalStateException (" MediaPlayer error ($what /$extra )" ))
185+ true
186+ }
187+ prepare()
185188 }
186- prepare()
187- start()
188189 }
189- }
190- val playback =
191- ActivePlayback (
192- cancel = {
193- finished.completeExceptionally(CancellationException (" assistant speech cancelled" ))
190+ val playback =
191+ ActivePlayback (
192+ cancel = {
193+ finished.completeExceptionally(CancellationException (" assistant speech cancelled" ))
194+ runCatching { player.stop() }
195+ },
196+ )
197+ register(playback)
198+ try {
199+ withContext(Dispatchers .Main ) {
200+ player.start()
201+ }
202+ finished.await()
203+ } finally {
204+ clear(playback)
205+ withContext(Dispatchers .Main ) {
194206 runCatching { player.stop() }
195- },
196- )
197- register(playback)
198- try {
199- finished.await()
200- } finally {
201- clear(playback)
202- withContext(Dispatchers .Main ) {
203- runCatching { player.stop() }
204- player.release()
207+ player.release()
208+ }
205209 }
210+ } finally {
206211 withContext(Dispatchers .IO ) {
207212 tempFile.delete()
208213 }
0 commit comments