audio_service
this plugin wraps around your existing audio code to allow it to run in the background or with the screen turned off, and allows your app to interact with headset buttons, the android lock screen and notification, ios control center, wearables and android auto. it is suitable for:
- music players
- text-to-speech readers
- podcast players
- video players
- navigators
- more!
how does this plugin work?
you encapsulate your audio code in a background task which runs in a special isolate that continues to run when your ui is absent. your background task implements callbacks to respond to playback requests coming from your flutter ui, headset buttons, the lock screen, notification, ios control center, car displays and smart watches:
you can implement these callbacks to play any sort of audio that is appropriate for your app, such as music files or streams, audio assets, text to speech, synthesised audio, or combinations of these.
feature | android | ios | macos | web |
---|---|---|---|---|
background audio | ✅ | ✅ | ✅ | ✅ |
headset clicks | ✅ | ✅ | ✅ | ✅ |
start/stop/play/pause/seek/rate | ✅ | ✅ | ✅ | ✅ |
fast forward/rewind | ✅ | ✅ | ✅ | ✅ |
repeat/shuffle mode | ✅ | ✅ | ✅ | ✅ |
queue manipulation, skip next/prev | ✅ | ✅ | ✅ | ✅ |
custom actions | ✅ | ✅ | ✅ | ✅ |
custom events | ✅ | ✅ | ✅ | ✅ |
notifications/control center | ✅ | ✅ | ✅ | ✅ |
lock screen controls | ✅ | ✅ | ✅ | |
album art | ✅ | ✅ | ✅ | ✅ |
android auto, apple carplay | (untested) | ✅ |
if you’d like to help with any missing features, please join us on the github issues page.
migrating to 0.14.0
audio focus, interruptions (e.g. phone calls), mixing, ducking and the configuration of your app’s audio category and attributes, are now handled by the audio_session package. read the migration guide for details.
can i make use of other plugins within the background audio task?
yes! audio_service
is designed to let you implement the audio logic however you want, using whatever plugins you want. you can use your favourite audio plugins such as just_audio, flutter_radio, flutter_tts, and others, within your background audio task. there are also plugins like just_audio_service that provide default implementations of backgroundaudiotask
to make your job easier.
note that this plugin will not work with other audio plugins that overlap in responsibility with this plugin (i.e. background audio, ios control center, android notifications, lock screen, headset buttons, etc.)
example
ui code
wrap your /
route’s widget tree in an audioservicewidget
:
void main() => runapp(new myapp());
class myapp extends statelesswidget {
@override
widget build(buildcontext context) {
return materialapp(
title: 'audio service demo',
home: audioservicewidget(child: mainscreen()),
);
}
}
start/stop your background audio task:
await audioservice.start(backgroundtaskentrypoint: _entrypoint);
await audioservice.stop();
standard controls:
audioservice.play();
audioservice.seekto(duration(seconds: 10));
audioservice.setspeed(1.5);
audioservice.pause();
queue management:
var item = mediaitem(
id: 'https://example.com/audio.mp3',
album: 'album name',
title: 'track title',
);
audioservice.addqueueitem(item);
audioservice.addqueueitemat(item, 1);
audioservice.removequeueitem(item);
audioservice.updatequeue([item, ...]);
audioservice.skiptonext();
audioservice.skiptoprevious();
audioservice.playfrommediaid('https://example.com/audio.mp3')
audioservice.playmediaitem(item);
looping and shuffling:
audioservice.setrepeatmode(audioservicerepeatmode.one); // none/one/all/group
audioservice.setshufflemode(audioserviceshufflemode.all); // none/all/group
custom actions:
audioservice.customaction('setvolume', 0.8);
audioservice.customaction('savebookmark');
listening to state changes:
audioservice.playbackstatestream.listen((playbackstate state) {
if (state.playing) ... else ...
switch (state.processingstate) {
case audioprocessingstate.none: ...
case connecting: ...
case ready: ...
case buffering: ...
case fastforwarding: ...
case rewinding: ...
case skippingtoprevious: ...
case skippingtonext: ...
case skippingtoqueueitem: ...
case completed: ...
case stopped: ...
case error: ...
}
});
listen to changes to the currently playing item:
audioservice.currentmediaitemstream.listen((mediaitem item) { ... });
listen to changes to the queue:
audioservice.queuestream.listen((list<mediaitem> queue) { ... });
listen to changes to the current playback position:
audioservice.positionstream.listen((duration position) { ... });
background code
define a background audio task to handle callbacks for all methods called from your ui or other clients (e.g. the media notification):
// must be a top-level function
void _entrypoint() => audioservicebackground.run(() => audioplayertask());
class audioplayertask extends backgroundaudiotask {
final _player = audioplayer(); // e.g. just_audio
// implement callbacks here. e.g. onstart, onstop, onplay, onpause
}
the purpose of this class is to encapsulate all audio logic in your app so that it is completely self-contained, and can continue to run on its own even when the flutter ui is not present. every message that you send from your flutter ui (start
, stop
, play
, pause
) has a corresponding callback that you can implement in your background audio task (onstart
, onstop
, onplay
, onpause
). additionally, there are callbacks that respond only to events outside of your flutter ui, such as onclick
, which responds to a click of a headset button, and onclose
which responds to the user swiping away the android media notification.
most of these callbacks can be implemented by simply delegating to your audio player plugin:
onplay() => _player.play();
onpause() => _player.pause();
onseekto(duration duration) => _player.seekto(duration);
onsetspeed(double speed) => _player.setspeed(speed);
your custom actions may be handled via a switch:
oncustomaction(string name, dynamic arguments) async {
switch (name) {
case 'setvolume':
_player.setvolume(arguments);
break;
case 'savebookmark':
// app-specific code
break;
}
}
onstart
is the place to initialise the player, and (usually) start playing audio:
onstart(map<string, dynamic> params) async {
final mediaitem = mediaitem(
id: "https://foo.bar/baz.mp3",
album: "foo",
title: "bar",
);
// tell the ui and media notification what we're playing.
audioservicebackground.setmediaitem(mediaitem);
// listen to state changes on the player...
_player.playerstatestream.listen((playerstate) {
// ... and forward them to all audio_service clients.
audioservicebackground.setstate(
playing: playerstate.playing,
// every state from the audio player gets mapped onto an audio_service state.
processingstate: {
processingstate.none: audioprocessingstate.none,
processingstate.loading: audioprocessingstate.connecting,
processingstate.buffering: audioprocessingstate.buffering,
processingstate.ready: audioprocessingstate.ready,
processingstate.completed: audioprocessingstate.completed,
}[playerstate.processingstate],
// tell clients what buttons/controls should be enabled in the
// current state.
controls: [
playerstate.playing ? mediacontrol.pause : mediacontrol.play,
mediacontrol.stop,
],
);
});
// play when ready.
_player.play();
// start loading something (will play when ready).
await _player.seturl(mediaitem.id);
}
the above implementation starts playing an initial media item, and also listens to state changes in the underlying player and broadcasts them to all audio_service clients (the flutter ui, media notification, smart watches, etc.) so that they may update their ui state. there are 3 methods by which your background audio task can broadcast state changes to clients:
audioservicebackground.setstate
broadcasts the current playback state to all clients. this includes whether or not audio is playing, but also whether audio is buffering, the current playback position and buffer position, the current playback speed, and the set of audio controls that should be made available. it is important for you to call this method whenever any of these pieces of state changes.audioservicebackground.setmediaitem
broadcasts information about the currently playing media item to all clients. this includes the track title, artist, genre, duration, any artwork to display, and other information.audioservicebackground.setqueue
broadcasts the current queue to all clients. some clients like android auto may display this information in their user interfaces.
onstop
is the place to dispose of any resources, stop playing audio, and shut down the background isolate:
onstop() async {
// stop and dispose of the player.
await _player.dispose();
// shut down the background task.
await super.onstop();
}
}
if you are instead building a text-to-speech reader, you could implement these callbacks differently:
import 'package:flutter_tts/flutter_tts.dart';
class readerbackgroundtask extends backgroundaudiotask {
final _tts = fluttertts();
string article;
onstart() async {
// tell clients what we're listening to
await audioservicebackground.setmediaitem(mediaitem(album: "business insider", ...));
// tell clients that we're now playing
await audioservicebackground.setstate(
playing: true,
processingstate: audioprocessingstate.ready,
controls: [mediacontrol.stop],
);
// play a small amount of silent audio on android to pose as an audio player
audioservicebackground.androidforceenablemediabuttons();
// start speaking
_tts.speak(article);
}
onstop() async {
await _tts.stop();
await audioservicebackground.setstate(
playing: false,
processingstate: audioprocessingstate.stopped,
controls: [mediacontrol.play],
);
await super.onstop();
}
}
see the full example for how to handle queues/playlists, headset button clicks and media artwork.
note that your ui and background task run in separate isolates and do not share memory. the only way they communicate is via message passing. your flutter ui will only use the audioservice
api to communicate with the background task, while your background task will only use the audioservicebackground
api to interact with the ui and other clients.
connecting to audioservice
from the background
you can also send messages to your background audio task from another background callback (e.g. android_alarm_manager) by manually connecting to it:
await audioservice.connect(); // note: the "await" is necessary!
audioservice.play();
configuring the audio session
if your app uses audio, you should tell the operating system what kind of usage scenario your app has and how your app will interact with other audio apps on the device. different audio apps often have unique requirements. for example, when a navigator app speaks driving instructions, a music player should duck its audio while a podcast player should pause its audio. depending on which one of these three apps you are building, you will need to configure your app’s audio settings and callbacks to appropriately handle these interactions.
use the audio_session package to change the default audio session configuration for your app. e.g. for a podcast player, you may use:
final session = await audiosession.instance;
await session.configure(audiosessionconfiguration.speech());
each time you invoke an audio plugin to play audio, that plugin will activate your app’s shared audio session to inform the operating system that your app is actively playing audio. depending on the configuration set above, this will also inform other audio apps to either stop playing audio, or possibly continue playing at a lower volume (i.e. ducking). you normally do not need to activate the audio session yourself, however if the audio plugin you use does not activate the audio session, you can activate it yourself:
// activate the audio session before playing audio.
if (await session.setactive(true)) {
// now play audio.
} else {
// the request was denied and the app should not play audio
}
when another app activates its audio session, it similarly may ask your app to pause or duck its audio. once again, the particular audio plugin you use may automatically pause or duck audio when requested. however, if it does not, you can respond to these events yourself by listening to session.interruptioneventstream
. similarly, if the audio plugin doesn’t handle unplugged headphone events, you can respond to these yourself by listening to session.becomingnoisyeventstream
. for more information, consult the documentation for audio_session.
note: if your app uses a number of different audio plugins, e.g. for audio recording, or text to speech, or background audio, it is possible that those plugins may internally override each other’s audio session settings since there is only a single audio session shared by your app. therefore, it is recommended that you apply your own preferred configuration using audio_session after all other audio plugins have loaded. you may consider asking the developer of each audio plugin you use to provide an option to not overwrite these global settings and allow them be managed externally.
android setup
these instructions assume that your project follows the new project template introduced in flutter 1.12. if your project was created prior to 1.12 and uses the old project structure, you can update your project to follow the new project template.
additionally:
- edit your project’s
androidmanifest.xml
file to declare the permission to create a wake lock, and add component entries for the<service>
and<receiver>
:
<manifest ...>
<uses-permission android:name="android.permission.wake_lock"/>
<uses-permission android:name="android.permission.foreground_service"/>
<application ...>
...
<service android:name="com.ryanheise.audioservice.audioservice">
<intent-filter>
<action android:name="android.media.browse.mediabrowserservice" />
</intent-filter>
</service>
<receiver android:name="com.ryanheise.audioservice.mediabuttonreceiver" >
<intent-filter>
<action android:name="android.intent.action.media_button" />
</intent-filter>
</receiver>
</application>
</manifest>
- starting from flutter 1.12, you will need to disable the
shrinkresources
setting in yourandroid/app/build.gradle
file, otherwise the icon resources used in the android notification will be removed during the build:
android {
compilesdkversion 28
...
buildtypes {
release {
signingconfig ...
shrinkresources false // add this line
}
}
}
ios setup
insert this in your info.plist
file:
<key>uibackgroundmodes</key>
<array>
<string>audio</string>
</array>
the example project may be consulted for context.
macos setup
the minimum supported macos version is 10.12.2 (though this could be changed with some work in the future).
modify the platform line in macos/podfile
to look like the following:
platform :osx, '10.12.2'
Comments are closed.