Audio Audio


Play audio, very simple! At any time, just run:

    import 'package:flame/flame.dart';
    
    Flame.audio.play('explosion.mp3');
    Flame.audio.playLongAudio('music.mp3');
Copy the code

Or, if you prefer:

    import 'package:flame/flame_audio.dart';
    
    FlameAudio audio = FlameAudio();
    
    audio.play('explosion.mp3');
    audio.playLongAudio('music.mp3');
Copy the code

The difference is that each instance shares a different cache. In general you should use the Flame. Audio instance, shared cache.

You must have the appropriate file structure to add files to pubspec.yaml files, as described above.

It can be an MP3,OGG or WAV file.

The purpose of using the AudioPlayers library is to allow multiple different audio to be played simultaneously (very important in the game). You can find a more detailed explanation in this library.

If you want to play indefinitely, just use the loop function.

    Flame.audio.loop('musci.mp3');
    Flame.audio.loopLongAudio('musci.mp3');
Copy the code

Alternatively, you can use Bgm to play background music on a loop. The Bgm class allows Flame to manage automatic pausing or restoring background music when pausing/resuming a game or application.

Play/loop and playLongAudio/loopLongAudio, is the difference between a play/loop using the optimized attribute, the audio in iteration cycle, didn’t break, and the frame rate almost not lost. You should always use this method. PlayLongAudio/loopLongAudio allowed to play any audio length, but they do cause lost frame rate, and the iteration loop audio there will be a little delay.

Finally, you can preload audio. Audio should be stored in memory the first time it is used; So when you play each MP3 for the first time, you might have a delay. To preload the audio, just use:

Flame.audio.load('explosion.mp3');
Copy the code

In the beginning, you can load all the audio so it plays smoothly; To load multiple sounds, use the loadAll method:

Flame.audio.loadAll(['explosion.mp3'.'music.mp3'])
Copy the code

Finally, you can remove it from the cache using the clear method:

    Flame.audio.clear('explosion.mp3');
Copy the code

There is also a clearAll method to clearAll caches.

This can be very useful, for example, when your game has many levels and each level has a different soundtrack.

Both load methods return a Future for all loaded files.

For both play and loop you can pass an additional optional double variable volume(the default is 1.0).

Both play and loop methods return an instance of the AudioPlayer from audioPlayers, which allows you to stop, pause, and configure other features.

There is a lot of logging, which was a feature of the original AudioPlayer plugin. They are useful for debugging, but you can disable them later:

Flame.audio.disableLog();
Copy the code