Skip to content
Merged
Show file tree
Hide file tree
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
24 changes: 21 additions & 3 deletions packages/flame_audio/lib/bgm.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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<void> 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;
}
Comment on lines +80 to +82

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, but this one predates this PR: before it the older play also resumed, so the wrong track played outright, and this PR only stops that extra resume. Serialising setup with a lock changes how overlapping play calls behave, so I would rather open it as a follow-up. Happy to add it here instead if you prefer.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it is better to fix this separately.

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<void> stop() async {
_playId++;
isPlaying = false;
await audioPlayer.stop();
}
Expand Down
124 changes: 124 additions & 0 deletions packages/flame_audio/test/bgm_test.dart
Original file line number Diff line number Diff line change
@@ -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<Completer<void>> 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<void>();
pendingSources.add(completer);
return completer.future;
});
when(() => player.resume()).thenAnswer((_) async {});
when(() => player.stop()).thenAnswer((_) async {});
bgm = Bgm()..audioPlayer = player;
});

Future<void> untilSourceIsLoading(int count) async {
while (pendingSources.length < count) {
await Future<void>.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<void>();
when(() => player.resume()).thenAnswer((_) => resuming.future);
final playing = bgm.play('song.mp3');
await untilSourceIsLoading(1);
pendingSources.single.complete();
await Future<void>.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);
});
});
}
Loading