1

I'm using the just_audio package, I have a playlist, and after playing all the tracks, the current index remains equal to the index of the last track. Is there a way to make the index equal to 0 when the playlist ends?

final myPlayList = ConcatenatingAudioSource(
  children: listAudios,
);
await _player.setAudioSource(myPlayList, initialIndex: 0, preload: false);
JM Apps
  • 150
  • 1
  • 7

1 Answers1

4

Listen for the completed state and seek to index 0. Assuming you also want to stop playing at that point, call pause() too:

_player.processingStateStream.listen((state) async {
  if (state == ProcessingState.completed) {
    await _player.pause();
    await _player.seek(Duration.zero, index: 0);
  }
});

Regarding the call to pause(): just_audio state is a composite of playing and processingState and you will only hear audio when playing=true, processingState=ready which is what you have during normal playback. The playing state only ever changes when you tell it to change, but the processingState may change independently depending on what is happening in the audio.

When reaching the end of the playlist, it will transition to playing=true, processingState=completed, hence no audio. If you seek back to the beginning, it will be playing=true, processingState=ready so you'll hear the audio automatically start back up. This may surprise you, but think of it as comparable to what happens in a YouTube video after it completes, but if you seek to the beginning it continues playing (because it's now ready, not completed).

If you want it to stop playing, you need to actually set playing=false with either pause() or stop(), where the former keeps things in memory, and the latter releases all resources.

For more information about the state model and its rationale, see The State Model section of the README.

Ryan Heise
  • 2,273
  • 5
  • 14
  • In this case, the playlist is played over and over again. **UPD** worked as `player.stop()` added. Could you fix the library so that the player has this behavior out of the box? – JM Apps Aug 08 '22 at 06:47
  • The library is working as intended, you can read the README section on how the state model works, but I have also updated my answer to explain it. – Ryan Heise Aug 08 '22 at 06:57