Skip to content

Instantly share code, notes, and snippets.

@henry2man
Last active January 25, 2021 19:46
Show Gist options
  • Save henry2man/d4ebc3c3515b9513d3ab5d25210208aa to your computer and use it in GitHub Desktop.
Save henry2man/d4ebc3c3515b9513d3ab5d25210208aa to your computer and use it in GitHub Desktop.
A simple Dart class that wraps all audio capabilities (sounds, concurrent fx and background music) for Flutter games.
class GameAudio {
AudioPool _pool;
String path;
bool isFx;
bool concurrent;
GameAudio(
{@required this.path,
this.concurrent: false,
this.isFx: true,
String prefix: "sfx"}) {
initInstanceAsync(prefix).then((value) =>
Log.v(_lP, "Sound $path loaded"));
}
Future<void> initInstanceAsync(String prefix) async {
this.isFx = isFx;
if (isFx) {
int minPlayers = concurrent ? 8 : 1;
int maxPlayers = concurrent ? 16 : 3;
this._pool = AudioPool(path,
prefix: "audio/sfx/", minPlayers: minPlayers, maxPlayers: maxPlayers);
this._pool.init();
} else {
this.path = "$prefix/$path";
Flame.audio.load(path);
}
}
void _play() async {
if (this.isFx) {
_pool.start();
if(concurrent) {
Log.v(_lP,
"Current available audioplayers: ${_pool.availablePlayers.length}");
}
} else {
Flame.bgm.play(path, volume: 0.8);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment