Flutter audio_service implement skipToNext without queue

I have a long audio file that has different sections. I have a Map containing where those sections start.

I want to implement skipToNext() and skipToPrevious methods for it.

I have access to the map inside BackgroundAudioTask.

I have implemented onSkipToNext like this:

 @override
  Future<void> onSkipToNext() async => () {
        print('next pressed');
        final currentIndex = _getCurrentTrackIndex(_player.position);
        print(currentIndex);
        if (currentIndex < _tracks.length - 1) {
          _player.seek(
            Duration(milliseconds: _tracks[currentIndex + 1]['start']),
          );
        }
      };

The _tracks looks like this:

[{id: 1, title: INTRODUCTION, start: 0}, {id: 2, title: Next track, start: 68347},]

But when I press on MediaControl.skipToNext from the notification or AudioService.skipToNext(); from Flutter UI.

It is not working i.e next pressed is not showing in the console and the audio is not working.

Am I doing something wrong? Can't I press MediaControl.skipToNext if there is no queue?

If I cannot do so, how can I implement such a feature?

Note: I am using just_audio for playing audio

Edit: Here's my systemActions

systemActions: [
  MediaAction.seekTo,
  MediaAction.seekForward,
  MediaAction.seekBackward,
  MediaAction.skipToNext,
  MediaAction.skipToPrevious,
],

Solved: Incorrect implementation of onSkipToNext() was the case of the problem as the accepted answer suggests.

Upvotes: 1

Views: 783

Answers (1)

Ryan Heise
Ryan Heise

Reputation: 2786

Assuming everything else works and it's just these two skip actions that don't work, the first thing you will need to do is include skipToNext and skipToPrevious in the controls parameter of AudioServiceBackground.setState rather than systemActions. systemActions is only for things that are not clickable buttons (e.g. seekTo).

You must also pass androidEnableQueue: true to AudioService.start if you want these queue-skipping actions to work on Android.

For completeness, I'll also just mention that none of the notification buttons (or headset buttons) will work on Android unless you have declared the broadcast receiver in your AndroidManifest.xml file:

        <receiver android:name="com.ryanheise.audioservice.MediaButtonReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.MEDIA_BUTTON" />
            </intent-filter>
        </receiver> 

But aside from all of those things, I notice your code contains a subtle programming error that is unrelated to audio_service. Your implementation of onSkipToNext simply returns a closure () { ... } so even if this callback is being called, the code inside the closure isn't being called. So you need to replace => () { ... } by { ... }.

Upvotes: 1

Related Questions