play method

Future<void> play(
  1. String filename, {
  2. double volume = 1.0,
})

Plays and loops a background music file specified by filename.

The volume can be specified in the optional named parameter volume where 0 means off and 1 means max.

It is safe to call this function even when a current BGM track is playing.

Implementation

Future<void> play(String filename, {double volume = 1.0}) async {
  //AudioService service = Provider.of<AudioService>(context);
  SharedPreferences prefs = await SharedPreferences.getInstance();
  double? vol = prefs.getDouble('voiceValue');

  final currentPlayer = player;

  if (isPlaying == false) {
    isPlaying = true;

    player?.open(
      new Playlist(
        playlistMode: PlaylistMode.single,
        medias: [
          Media.asset('assets/audio/' + filename + ".mp3"),
        ],
      ),
    );
    player?.setVolume(vol ?? 1.0);
  } else {
    currentPlayer?.stop();

    player?.open(
      new Playlist(
        playlistMode: PlaylistMode.single,
        medias: [
          Media.asset('assets/audio/' + filename + ".mp3"),
        ],
      ),
    );
    player?.setVolume(vol ?? 1.0);
  }
}