Looping Background Music


The Bgm class is responsible for managing background music related to state changes in the application (or game) life cycle.

When the application pauses, terminates, or is sent to the background, Bgm automatically pauses the music track that is playing. Similarly, when the program resumes, Bgm will also restore the background music. Manual pause and resume are also supported.

In order for the Bgm class to function properly, observers must be registered by:

    Flame.bgm.initialize();
Copy the code

Important: The Initialize method must be called only when an instance of the WidgetsBinding class already exists. After runApp has been called at least once, you can assume that this is true.

Dispose method to remove observer after background music has stopped but you want to keep the app/game running.

    Flame.bgm.dispose();
Copy the code

To loop the background music, run the following:

    import 'package:flame/flame/dart';
    Flame.bgm.play('adventure-track.mp3');
Copy the code

Or, if you prefer:

    import 'package:flame/bgm.dart';
    
    Bgm audio = Bgm();
    audio.play('adventure-track.mp3');
Copy the code

Note: The Bgm class will always use a static instance of FlameAudio in the Flame. Audio package to hold cached music files.

You must have a proper file structure and add the file to pubspec.yaml as explained in the Flame audio document.

Caching music files


The following methods can be used to preload (and unload) music files into the cache. These methods are just aliases in Flame. Audio and have the same name.

Again, if you need more information, check out the Flame audio documentation.

    Flame.audio.load('adventure-track.mp3');
    Flame.audio.loadAll([
        'menu.mp3'.'dungeon.mp3',]); Flame.audio.clear('adventure-track.mp3');
    Flame.bgm.clearAll();
Copy the code

methods


play

The Play method receives a String variable that points to the name of the file to play the music (follow the Flame Audio folder structure requirements).

You can pass additional optional double, volume variables (default is 1.0). Example:

    Flame.bgm.play('bgm/boss-fight/level-382.mp3');
Copy the code
    Flame.bgm.play('bgm/world-map.mp3',volume: .25);
Copy the code

suspended

Pause background music, using the stop method.

    Flame.bgm.stop();
Copy the code

Pause and Resume

To manually pause and resume background music, you can use pause and resume.

Flame. BGM automatically handles pausing and resuming playing background music tracks. Manually pausing this feature prevents the application/game from automatically resuming when the focus is reassigned to it.

    Flame.bgm.pause();
Copy the code
    Flame.bgm.resume();
Copy the code