Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix when play music in background thread, play state will change wrong #1335

Open
wants to merge 1 commit into
base: minor
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 26 additions & 18 deletions just_audio/lib/just_audio.dart
Original file line number Diff line number Diff line change
Expand Up @@ -938,26 +938,34 @@ class AudioPlayer {
_playbackEventSubject.add(_playbackEvent);
final playCompleter = Completer<dynamic>();
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);
}
Expand Down