Skip to content

Commit

Permalink
fix: race condition causes multiple songs to play at the same time (#43)
Browse files Browse the repository at this point in the history
  • Loading branch information
diegoroyo committed Sep 1, 2021
1 parent be4fa32 commit ffdcd75
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 15 deletions.
39 changes: 24 additions & 15 deletions lib/providers/audio_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@ import 'package:app/utils/preferences.dart' as preferences;
import 'package:assets_audio_player/assets_audio_player.dart';
import 'package:flutter/cupertino.dart';
import 'package:rxdart/rxdart.dart';
import 'package:mutex/mutex.dart';

class AudioProvider with StreamSubscriber, ChangeNotifier {
SongProvider _songProvider;
InteractionProvider _interactionProvider;
Mutex _mutex;

late AssetsAudioPlayer _player;
AssetsAudioPlayer get player => _player;
Expand All @@ -22,7 +24,8 @@ class AudioProvider with StreamSubscriber, ChangeNotifier {
required SongProvider songProvider,
required InteractionProvider interactionProvider,
}) : _songProvider = songProvider,
_interactionProvider = interactionProvider;
_interactionProvider = interactionProvider,
_mutex = Mutex();

Future<void> init() async {
_player = AssetsAudioPlayer.newPlayer();
Expand Down Expand Up @@ -72,23 +75,29 @@ class AudioProvider with StreamSubscriber, ChangeNotifier {
}

Future<void> play({Song? song}) async {
if (song == null) {
return await _player.play();
}
await _mutex.acquire();

int index = await indexInQueue(song);
try {
if (song == null) {
return await _player.play();
}

if (index != -1) {
await _player.playlistPlayAtIndex(index);
} else {
await _player.playlistPlayAtIndex(
_player.current.hasValue
? await queueAfterCurrent(song: song)
: await queueToTop(song: song),
);
}
int index = await indexInQueue(song);

await _player.play();
if (index != -1) {
await _player.playlistPlayAtIndex(index);
} else {
await _player.playlistPlayAtIndex(
_player.current.hasValue
? await queueAfterCurrent(song: song)
: await queueToTop(song: song),
);
}

await _player.play();
} finally {
_mutex.release();
}
}

Future<void> stop() async => await _player.stop();
Expand Down
7 changes: 7 additions & 0 deletions pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,13 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "5.0.12"
mutex:
dependency: "direct main"
description:
name: mutex
url: "https://pub.dartlang.org"
source: hosted
version: "3.0.0"
nested:
dependency: transitive
description:
Expand Down
1 change: 1 addition & 0 deletions pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ dependencies:
uuid: ^3.0.4
golden_toolkit: ^0.9.0
fake_async: ^1.2.0
mutex: ^3.0.0

dev_dependencies:
flutter_test:
Expand Down

0 comments on commit ffdcd75

Please sign in to comment.