From 8ff286bbfe5f9b516c0f02a875876d11cc532555 Mon Sep 17 00:00:00 2001 From: zhushenwudi <30340027+zhushenwudi@users.noreply.github.com> Date: Tue, 24 Sep 2024 07:17:05 +0800 Subject: [PATCH] fix when play music in background thread, play state will change wrong --- just_audio/lib/just_audio.dart | 44 ++++++++++++++++++++-------------- 1 file changed, 26 insertions(+), 18 deletions(-) diff --git a/just_audio/lib/just_audio.dart b/just_audio/lib/just_audio.dart index 591fcf781..81fd69748 100644 --- a/just_audio/lib/just_audio.dart +++ b/just_audio/lib/just_audio.dart @@ -938,26 +938,34 @@ class AudioPlayer { _playbackEventSubject.add(_playbackEvent); final playCompleter = Completer(); final audioSession = await AudioSession.instance; - if (!_handleAudioSessionActivation || await audioSession.setActive(true)) { - if (!playing) return; - // TODO: rewrite this to more cleanly handle simultaneous load/play - // requests which each may result in platform play requests. - final requireActive = _audioSource != null; - if (requireActive) { - if (_active) { - // If the native platform is already active, send it a play request. - // NOTE: If a load() request happens simultaneously, this may result - // in two play requests being sent. The platform implementation should - // ignore the second play request since it is already playing. - _sendPlayRequest(await _platform, playCompleter); - } else { - // If the native platform wasn't already active, activating it will - // implicitly restore the playing state and send a play request. - _setPlatformActive(true, playCompleter: playCompleter) - ?.catchError((dynamic e) async => null); + try { + if (!_handleAudioSessionActivation || await audioSession.setActive(true)) { + if (!playing) return; + + // TODO: rewrite this to more cleanly handle simultaneous load/play + // requests which each may result in platform play requests. + final requireActive = _audioSource != null; + if (requireActive) { + if (_active) { + // If the native platform is already active, send it a play request. + _sendPlayRequest(await _platform, playCompleter); + } else { + // If the native platform wasn't already active, activating it will + // implicitly restore the playing state and send a play request. + _setPlatformActive(true, playCompleter: playCompleter) + ?.catchError((dynamic e) async => null); + } } + } else { + // Revert if we fail to activate the audio session. + _playingSubject.add(false); + } + } catch (e) { + // Handle the PlatformException + if (e is PlatformException) { + // Log the exception if needed + print('Failed to activate audio session in background thread'); } - } else { // Revert if we fail to activate the audio session. _playingSubject.add(false); }