diff --git a/packages/flame_audio/lib/bgm.dart b/packages/flame_audio/lib/bgm.dart index e86dbaaecfb..927b746d407 100644 --- a/packages/flame_audio/lib/bgm.dart +++ b/packages/flame_audio/lib/bgm.dart @@ -23,6 +23,10 @@ class Bgm({AudioCache? audioCache}) extends WidgetsBindingObserver { /// Whether [Bgm] is playing or not. bool isPlaying = false; + /// Counts the calls to [play] and [stop], so that a [play] that is still + /// loading knows when it has been replaced or stopped. + int _playId = 0; + /// Registers a [WidgetsBinding] observer. /// /// This must be called for auto-pause and resume to work properly. @@ -60,23 +64,37 @@ class Bgm({AudioCache? audioCache}) extends WidgetsBindingObserver { /// where `0` means off and `1` means max. /// /// It is safe to call this function even when a current BGM track is - /// playing. + /// playing. If [stop] or [play] is called before the track has loaded, this + /// track does not start. Future play( String fileName, { double volume = 1, String? package, }) async { + final playId = ++_playId; await audioPlayer.release(); await audioPlayer.setReleaseMode(ReleaseMode.loop); await audioPlayer.setVolume(volume); final path = package == null ? fileName : 'packages/$package/$fileName'; await audioPlayer.setSource(AssetSource(path)); - await audioPlayer.resume(); + if (playId != _playId) { + return; + } isPlaying = true; + try { + await audioPlayer.resume(); + } catch (_) { + if (playId == _playId) { + isPlaying = false; + } + rethrow; + } } - /// Stops the currently playing background music track (if any). + /// Stops the currently playing background music track (if any), including + /// one that [play] is still loading. Future stop() async { + _playId++; isPlaying = false; await audioPlayer.stop(); } diff --git a/packages/flame_audio/test/bgm_test.dart b/packages/flame_audio/test/bgm_test.dart new file mode 100644 index 00000000000..c6af3a0f7e2 --- /dev/null +++ b/packages/flame_audio/test/bgm_test.dart @@ -0,0 +1,124 @@ +import 'dart:async'; + +import 'package:audioplayers/audioplayers.dart'; +import 'package:flame_audio/bgm.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class _MockAudioPlayer() extends Mock implements AudioPlayer; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUpAll(() { + registerFallbackValue(AssetSource('')); + registerFallbackValue(ReleaseMode.loop); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + for (final name in [ + 'xyz.luan/audioplayers', + 'xyz.luan/audioplayers.global', + ]) { + messenger.setMockMethodCallHandler( + MethodChannel(name), + (_) async => null, + ); + } + }); + + group('Bgm', () { + late _MockAudioPlayer player; + late Bgm bgm; + late List> pendingSources; + + setUp(() { + player = _MockAudioPlayer(); + pendingSources = []; + when(() => player.release()).thenAnswer((_) async {}); + when(() => player.setReleaseMode(any())).thenAnswer((_) async {}); + when(() => player.setVolume(any())).thenAnswer((_) async {}); + when(() => player.setSource(any())).thenAnswer((_) { + final completer = Completer(); + pendingSources.add(completer); + return completer.future; + }); + when(() => player.resume()).thenAnswer((_) async {}); + when(() => player.stop()).thenAnswer((_) async {}); + bgm = Bgm()..audioPlayer = player; + }); + + Future untilSourceIsLoading(int count) async { + while (pendingSources.length < count) { + await Future.delayed(Duration.zero); + } + } + + test('stop while play is still loading keeps the music stopped', () async { + final playing = bgm.play('song.mp3'); + await untilSourceIsLoading(1); + + await bgm.stop(); + pendingSources.single.complete(); + await playing; + + verifyNever(() => player.resume()); + expect(bgm.isPlaying, isFalse); + }); + + test('play after stop starts the music', () async { + await bgm.stop(); + final playing = bgm.play('song.mp3'); + await untilSourceIsLoading(1); + pendingSources.single.complete(); + await playing; + + verify(() => player.resume()).called(1); + expect(bgm.isPlaying, isTrue); + }); + + test('stop while the music is starting leaves isPlaying false', () async { + final resuming = Completer(); + when(() => player.resume()).thenAnswer((_) => resuming.future); + final playing = bgm.play('song.mp3'); + await untilSourceIsLoading(1); + pendingSources.single.complete(); + await Future.delayed(Duration.zero); + + await bgm.stop(); + resuming.complete(); + await playing; + + verify(() => player.stop()).called(1); + expect(bgm.isPlaying, isFalse); + }); + + test( + 'play while another play is loading starts only the last one', + () async { + final first = bgm.play('first.mp3'); + await untilSourceIsLoading(1); + + final second = bgm.play('second.mp3'); + await untilSourceIsLoading(2); + pendingSources[1].complete(); + await second; + pendingSources[0].complete(); + await first; + + verify(() => player.resume()).called(1); + expect(bgm.isPlaying, isTrue); + }, + ); + + test('play whose resume fails leaves isPlaying false', () async { + when(() => player.resume()).thenThrow(Exception('resume failed')); + final playing = bgm.play('song.mp3'); + await untilSourceIsLoading(1); + pendingSources.single.complete(); + + await expectLater(playing, throwsException); + expect(bgm.isPlaying, isFalse); + }); + }); +}