-
-
Notifications
You must be signed in to change notification settings - Fork 484
Cookbook
This page provides a cookbook of recipes to handle a variety of background audio use cases.
The cookbook is open to contributors.
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]
}
}