1

How can I play a list of (short) audio one by one using audioplayers?

I now have the following code:

  AudioPlayer? _player;
  void _play(number) async {
    _player?.dispose();
    final player = _player = AudioPlayer();
    print("trying to play number $number");
    player.play(AssetSource('audio/$number.wav'));
  }
...
  void _playList(list) async{
    for (int i=0;i<list.length;i++){
      _play(i);
    }
  }

But because I am creating multiple AudioPlayer objects here, the audios got played simultaneously.

What I want to achieve is: Play the first audio, wait until it reaches the end, then play the next audio. Loop until all the audios in the list got played.

Kaidi G
  • 43
  • 4
  • 2
    I am not an expert in Dart/Flutter, but you will probably have to make use of [`player.onPlayerStateChanged`](https://github.com/bluefireteam/audioplayers/blob/main/getting_started.md#state-event) listener to check if the state of the `AudioPlayer` is [`completed`](https://github.com/bluefireteam/audioplayers/blob/50f56365f8e512df0fc5bdb7222614389cbd4ea0/packages/audioplayers_platform_interface/lib/src/api/player_state.dart#LL13C3-L13C12) and then play the next song from the play list. Also, you do not have to make a new object of `AudioPlayer` for each song! – Jay May 11 '23 at 03:35
  • @Jay Thanks a lot for the tip, I end up using the onPlayerComplete function to make it happen... – Kaidi G May 17 '23 at 02:35

1 Answers1

0

ok, I will answer my own question here.

  AudioPlayer player= AudioPlayer();
  void _playList(list) async{
    player.play(AssetSource('audio/${list[0]}.wav'));
    int i =1;
    player.onPlayerComplete.listen((_) {
      if (i<list.length) {
        player.play(AssetSource('audio/${list[i]}.wav'));
        i++;
      }
    });
  }
Kaidi G
  • 43
  • 4
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 17 '23 at 04:53