diff --git a/lib/providers/audio_provider.dart b/lib/providers/audio_provider.dart index f706856..b714f8b 100644 --- a/lib/providers/audio_provider.dart +++ b/lib/providers/audio_provider.dart @@ -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; @@ -22,7 +24,8 @@ class AudioProvider with StreamSubscriber, ChangeNotifier { required SongProvider songProvider, required InteractionProvider interactionProvider, }) : _songProvider = songProvider, - _interactionProvider = interactionProvider; + _interactionProvider = interactionProvider, + _mutex = Mutex(); Future init() async { _player = AssetsAudioPlayer.newPlayer(); @@ -72,23 +75,29 @@ class AudioProvider with StreamSubscriber, ChangeNotifier { } Future 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 stop() async => await _player.stop(); diff --git a/pubspec.lock b/pubspec.lock index 96bc987..2cc7c4a 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -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: diff --git a/pubspec.yaml b/pubspec.yaml index c4e4aaf..7f7282d 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -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: