Search code examples
flutterplaylistjust-audio

Сompletion playlist and resetting index in just_audio


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);

Solution

  • 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.