Search code examples
flutterjust-audio

Flutter just_audio - seektoNext with LoopMode.one enabled


I would like to modify just_audio such that when LoopMode is set to LoopMode.one the seekToNext still goes to the next track in the playlist instead of repeating the same track. I would still want the track to repeat if it reaches the end without the user pressing the skip_next button. I believe this would be the expected behaviour from most users as this is how Spotify and most other music services function.

I tried a quick hack by modifying the code to momentarily disable LoopMode.one when the user presses the skip_next button but it seemed to just disable the button. I'm probably missing something obvious but any suggestions on the proper way to do this would be greatly appreciated.

        StreamBuilder<SequenceState?>(
          stream: player.sequenceStateStream,
          builder: (context, snapshot) => IconButton(
              icon: Icon(Icons.skip_previous),
              iconSize: 50.0,
              onPressed:
                  // default code
                  // player.hasNext ? player.seekToNext : null,
                  //  modified code below not working
                  () {
                if (player.loopMode == LoopMode.off ||
                    player.loopMode == LoopMode.all) {
                  player.hasNext ? player.seekToNext : null;
                } else if (player.loopMode == LoopMode.one) {
                  player.setLoopMode(LoopMode.off);
                  player.hasNext ? player.seekToNext : null;
                  player.setLoopMode(LoopMode.one);
                }
              }),
        ),

Solution

  • You can seek to the current index + 1:

    final nextIndex = player.currentIndex + 1;
    if (nextIndex < player.sequence.length) {
      player.seek(Duration.zero, nextIndex);
    }
    

    Note: if you are using shuffle mode, then use player.effectiveIndices to find the actual next index. For example, if it contains [3, 2, 1, 0] and currentIndex is 3, this list tells you that the nextIndex should be 2.