playBackgroundSound method

dynamic playBackgroundSound(
  1. String assetPath, {
  2. double volume = 1,
})

Plays a background song from the assets. This method is intended for long files. Currently it's possible to play only one background sound simultaneously. On the mobile platforms, the sound is paused while the game is out of focus.

If a song is already playing, applies crossfade. Does nothing if such a sound is already playing.

Implementation

playBackgroundSound(String assetPath, {double volume = 1}) async {
  if (assetPath == _currentlyPlayingAsset) return;

  try {
    if (_backgroundPlayer != null) {
      await smoothlyStopBackground(const Duration(milliseconds: 1000));
    }
    _backgroundPlayer = AudioPlayer();
    _backgroundPlayer?.setAsset(assetPath);
    _backgroundPlayer?.setVolume(0);
    _backgroundPlayer?.setLoopMode(LoopMode.one);
    _backgroundPlayer?.play();

    _currentlyPlayingAsset = assetPath;

    await lerpBackroundVolume(volume, const Duration(milliseconds: 1000));
  } catch (e) {
    log('[AUDIO] $e', error: e);
  }
}