Flutter Intermediate Lesson 114 of 135 2 min read
Sound Effects and Music in Flame with flame_audio
Add sound effects and background music to a Flutter Flame game with flame_audio: assets, FlameAudio.play, looping music, preloading and mute.
On this page
Sound makes a game feel finished: a “ping” when you collect a coin, a “boom” on a hit, music in the background. The flame_audio package handles both.
Sound files must be in your project, so this lesson’s code runs on your computer, not in the browser editor.
Install and add files
flutter pub add flame_audio
Put files in assets/audio/ and list the folder in pubspec.yaml:
flutter:
assets:
- assets/audio/
Use short .wav or .mp3 files for effects and .mp3 or .ogg for music. Free sounds: Kenney audio packs, freesound.org (check licences), or make your own with jsfxr.
Sound effects
// Not standalone: needs assets/audio/coin.wav
import 'package:flame_audio/flame_audio.dart';
// Anywhere in your game:
FlameAudio.play('coin.wav'); // plays once
FlameAudio.play('hit.wav', volume: 0.5); // quieter
Load sounds before they are first needed, so there is no delay on the first play:
@override
Future<void> onLoad() async {
await FlameAudio.audioCache.loadAll(['coin.wav', 'hit.wav', 'jump.wav']);
}
Background music
// Start looping music (for example when the game starts)
FlameAudio.bgm.initialize();
FlameAudio.bgm.play('music.mp3', volume: 0.4);
// Pause and resume with the game
FlameAudio.bgm.pause();
FlameAudio.bgm.resume();
// Stop when leaving the game screen
FlameAudio.bgm.stop();
bgm also pauses automatically when the app goes to the background, once it is initialised.
A mute setting
class Sfx {
static bool muted = false;
static void play(String file, {double volume = 1}) {
if (!muted) FlameAudio.play(file, volume: volume);
}
}
// In a collision:
Sfx.play('coin.wav');
Save muted with shared_preferences so the choice is remembered (see Saving the high score).
Web browsers and sound
Browsers block sound until the user has interacted with the page. Start music after the first tap (for example on the “Play” button of your main menu), not in onLoad.
Try it yourself
Add three sounds to one of the game projects: one when you score, one when you lose a life and one on game over.