Flutter just audio with audio services , how to handle button events

Viewed 34

How to handle next audio button pressed event and previous audio button event on flutter just audio with audio services , my audio files is encrypted , i must decrypt audio file before playing

mediaItem.add(MediaItem(id: "1", title: item.title!,artUri: Uri.file(PathHelper().pathAudio!+"name.mp3")));
_player.setFilePath(PathHelper().pathAudio!+"name.mp3");
1 Answers

I will just answer the main question about handling button events (I can't answer about encryption).

To handle button events, override these methods in your audio handler:

  • skipToNext
  • skipToPrevious
  • click

The first two handle next and previous buttons in various places including the notification, while click handles button presses on a headset. Since some headsets also also have next/previous buttons, and some headset emulate next/previous by long pressing on the volume buttons, etc., click can handle multiple types of events. For this reason, click takes a parameter indicating which of the 3 types of events occurred (next, previous or play/pause).

The default implementation of click is as follows:

  Future<void> click([MediaButton button = MediaButton.media]) async {
    switch (button) {
      case MediaButton.media:
        if (playbackState.valueOrNull?.playing == true) {
          await pause();
        } else {
          await play();
        }
        break;
      case MediaButton.next:
        await skipToNext();
        break;
      case MediaButton.previous:
        await skipToPrevious();
        break;
    }
  }

(Reference: API documentation)

Related