Skip to content
suragch edited this page Dec 7, 2020 · 2 revisions

This page provides a cookbook of recipes to handle a variety of background audio use cases.

The cookbook is open to contributors.

Have a button that plays a media item

First, make your background audio task aware of each media item you wish to play. This can be initiated by the background audio task itself with AudioServiceBackground.setQueue or by the UI with AudioService.addQueueItem. The official example already demonstrates how to use setQueue, so this cookbook example will assume you're instead calling addQueueItem from your Flutter UI passing in the media item details you want to play.

Second, in your button's onPressed, call AudioService.playFromMediaId with the id of your media item. It is common to use a URL as the id of your media item.

Your background audio task could be implemented like this:

class AudioPlayerTask extends BackgroundAudioTask {
  final _mediaItems = <String, MediaItem>{};
  final _completer = Completer();

  @override
  Future<void> onStart() async {
    // Don't actually play anything here. Just keep the isolate alive
    // until it's ready to shut down.
    // We are not calling setQueue here since we're allowing the UI
    // to add its own queue items.
    await _completer.future;
  }

  @override
  void onStop() {
    // stop playing. And also:
    _completer.complete();
  }

  @override
  void onAddQueueItem(MediaItem item) {
    // we're not actually maintaining a "queue", we're just keeping a map:
    _mediaItems[item.id] = item;
  }

  @override
  void onPlayFromMediaId(String mediaId) {
    // play the item at mediaItems[mediaId]
  }
}

problema con la cache 'package:audio_service/audio_service.dart': Failed assertion: line 917 pos 12: '_cacheManager == null': is not true.

Clone this wiki locally