play method

Future<void> play(
  1. String fileName, {
  2. double volume = 1,
  3. String? package,
})

Plays and loops a background music file specified by fileName.

The volume can be specified in the optional named parameter volume where 0 means off and 1 means max.

It is safe to call this function even when a current BGM track is playing.

Implementation

Future<void> play(
  String fileName, {
  double volume = 1,
  String? package,
}) async {
  await audioPlayer.release();
  await audioPlayer.setReleaseMode(ReleaseMode.loop);
  await audioPlayer.setVolume(volume);
  final path = package == null
      ? fileName
      : 'packages/$package/${audioPlayer.audioCache.prefix}$fileName';
  if (package != null) {
    final originalPrefix = audioPlayer.audioCache.prefix;
    audioPlayer.audioCache.prefix = '';
    await audioPlayer.setSource(AssetSource(path));
    audioPlayer.audioCache.prefix = originalPrefix;
  } else {
    await audioPlayer.setSource(AssetSource(path));
  }
  await audioPlayer.resume();
  isPlaying = true;
}