Looping Background Music¶
Bgm class you can manage looping of background music tracks with regards to application
(or game) lifecycle state changes.
When the application is terminated, or sent to background,
Bgm will automatically pause
the currently playing music track. Similarly, when the application is resumed,
Bgm will resume the
background music. Manually pausing and resuming your tracks is also supported.
Bgm class is handled by the flame_audio library
so you first have to add that to your dependency list in your
dependencies: flame_audio: 1.2.0
The latest version can be found on pub.dev.
For this class to function properly, the observer must be registered by calling the following:
IMPORTANT Note: The
initialize function must be called at a point in time where an instance of
WidgetsBinding class already exists. Best practice is to put this call inside of your game’s
In cases where you’re done with background music but still want to keep the application/game
running, use the
dispose function to remove the observer.
To play a looping background music track, run:
import 'package:flame_audio/flame_audio.dart'; FlameAudio.bgm.play('adventure-track.mp3');
Bgm class will always use the static instance of
FlameAudio for storing cached
You must have an appropriate folder structure and add the files to the
pubspec.yaml file, as
explained in Flame Audio documentation.
Caching music files¶
The following functions can be used to preload (and unload) music files into the cache. These
functions are just aliases for the ones in
FlameAudio with the same names.
Again, please refer to the Flame Audio documentation if you need more info.
import 'package:flame_audio/flame_audio.dart'; FlameAudio.bgm.load('adventure-track.mp3'); FlameAudio.bgm.loadAll([ 'menu.mp3', 'dungeon.mp3', ]); FlameAudio.bgm.clear('adventure-track.mp3'); FlameAudio.bgm.clearCache();
play function takes in a
String that should be a path that points to the location of the
music file to be played (following the Flame Audio folder structure requirements).
You can pass an additional optional
double parameter which is the
volume (defaults to
FlameAudio.bgm.play('bgm/world-map.mp3', volume: .25);
To stop a currently playing background music track, just call
Pause and Resume¶
To manually pause and resume background music you can use the
FlameAudio.bgm automatically handles pausing and resuming the currently playing background music
pausing prevents the app/game from auto-resuming when focus is given back to the