Skip to content
ryanheise edited this page Jun 17, 2020 · 32 revisions

Frequently Asked Questions

Why does nothing happen when calling AudioService.start()?

Make sure you have done the following:

  1. Your background task entrypoint must be a top-level function, i.e. not inside a class.
  2. If on Android, you must follow the Android setup instructions in the README file.

Why aren't my notification buttons and headset buttons working?

On Android, such button clicks are handled by a broadcast receiver which must be declared 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> 

If you configured your project prior to version 0.10.0, your old broadcast receiver configuration will no longer work and must be updated to the one above.

Why does my app get a MissingPluginException?

Make sure you have upgraded your project to the Flutter 1.12 project structure first. If you still get the error, it may be an issue of the specific combination of other plugins you're using. Make sure that the other plugins you're using have also been updated to support Flutter 1.12 (known as the v2 plugin model).

Why does the control center not appear on iOS?

This can result from a conflict with the flutter_tts plugin, which is also used in the example. (See the open issue #202)

Can this plugin be used with android_alarm_manager?

As of audio_service 0.9.0, a callback set by android_alarm_manager can connect to AudioService via AudioService.connect and communicate with a running background audio task, although currently is not allowed to start a new background audio task (this must be done from an activity, when the app is in the foreground).

Can this plugin be used with audioplayers

audioplayers has both worked and not worked at different times in the past. If it currently does not work, you can contact the author of that plugin and make a feature request.

Relevant information: For an audio player plugin to work with audio_service there needs to be clearly delineated roles between the two plugins such that only audio_service controls the various APIs involved in:

  1. Enabling background execution
  2. Displaying notifications, lock screen controls, Control Center info, etc.
  3. Configuring the audio session
  4. Handling remote controls from headsets, smart watches, car stereos, etc.
  5. Handling audio focus events (e.g. if another app takes over audio focus temporarily)

If the other plugin does any of these things, the two plugins will overlap in responsibility and things will probably not work. In other words, you will need an audio player plugin that just plays audio, and doesn't take on any of these other responsibilities listed above.

If at present audioplayers doesn't work for you, you can alternatively try my plugin just_audio which was designed with this delineation in mind.

Can I pause audio when receiving an incoming call?

Yes. In your background task, you must override the relevant callbacks:

  void onAudioFocusLost(AudioInterruption interruption) {}
  void onAudioFocusGained(AudioInterruption interruption) {}

When audio focus is lost, you need to observe and remember whether audio was playing at that time. When audio focus is gained, restore audio playback only if audio was originally playing when it was interrupted and the interruption parameter indicates that playback should resume as normal (see the documentation and example for further details).

Is it possible to make the headphone (media) buttons work in a text-to-speech app?

There is an issue on Android, but there is a workaround. Android requires an active media session to route media button events to, and actual audio needs to be played to activate a media session (text-to-speech does not qualify). One trick is to play a short segment of silent audio to activate the session. You can use AudioServiceBackground.androidForceEnableMediaButtons() to achieve this.

How do I send arbitrary initialisation messages to the background task when starting it?

Arbitrary parameters can be passed to AudioService.start via the params parameter. You can use AudioService.customAction(...) to pass an arbitrary message to the background task after it has started. To ensure it has started, you must await the result of AudioService.start:

if (await AudioService.start(...)) {
  AudioService.customAction(...);
}

How do I communicate between the UI and background isolates

As per the README file:

Keep in mind that your Flutter 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 clients, which include the Flutter UI.

There are a number of predefined messages you can pass from the UI to the background isolate via the AudioService API such as play, pause, seekTo, skipToNext, etc. If you want to send another message that is not one of the predefined messages in this API, you can use customAction (See "How do I send a custom action?").

There are also a number of predefined messages you can pass from the background to the UI isolate via the AudioServiceBackground API such as setState, setMediaItem and setQueue. If you want to send another message that is not one of the predefined messages in this API, you can use sendCustomEvent (See "How do I send a custom event?").

How do I send a custom action?

If you want to send a message from the UI to your background audio task but it is not one of the predefined messages defined in AudioService, you can send the message as a custom action. E.g.

// In your UI
await AudioService.customAction("setVolume", 0.5);

And then in your background audio task, implement the onCustomAction method:

@override
Future onCustomAction(String name, dynamic arguments) async {
    if (name == 'setVolume') {
        _audioPlayer.setVolume(arguments);
    }
}

Note that the parameter of a custom action can be any data structure that can be encoded by the standard message codec. If you return a value from onCustomAction, it will also be returned back to the caller of customAction.

How do I send a custom event?

If you want to send an event from your background audio task to the Flutter UI but it is not one of the predefined messages defined in AudioServiceBackground, you can send the message as a custom event. E.g.

// In your background task
AudioServiceBackground.sendCustomEvent("itHappened");

And then in your Flutter UI:

AudioService.customEventStream.listen((event) {
  print("Received event: $event");
}

The event parameter can contain any data permitted by Dart's SendPort/ReceivePort API. Please consult the relevant documentation for further information. This means that you can create your own application-specific event class encapsulating event data relevant to your app.

How do I update an existing MediaItem?

You cannot update fields in a MediaItem object since it is immutable, although in the same style as ThemeData.copyWith, you can use MediaItem.copyWith to create a copy with some fields modified. e.g.

modifiedMediaItem = mediaItem.copyWith(duration: duration);

If you are updating the current media item in your background audio task, remember to broadcast this change to all clients:

AudioServiceBackground.setMediaItem(modifiedMediaItem);

If you are updating a media item in the queue in your background audio task, remember to broadcast your modified queue to all clients:

myQueue[pos] = modifiedMediaItem;
AudioServiceBackground.setQueue(myQueue);

How can I stop the background task when the user swipes away the app in the task manager?

For Android, you can override the onTaskRemoved callback to control what happens when the user swipes away the task in the task manager. By default, the operating system will just clear your app's activity (UI) from memory leaving your service to run in the background with the audio. But you can override this callback as follows to cause your service to also be shut down:

  void onTaskRemoved() {
    onStop();
  }

If you use the androidStopForegroundOnPause option, when your audio is paused, the operating system moves your service to a lower priority level where it can be destroyed at any time to reclaim memory. If the user swipes away your task under these conditions, the operating system will destroy your service, and you may override this method to do any cleanup. For example:

  void onTaskRemoved() {
    if (!AudioServiceBackground.state.playing) {
      onStop();
    }
  }

How do I test the latest code on git master?

Sometimes you may want to try out the latest code on git master, e.g. to try out a bug fix or new feature that hasn't been released yet. To do so, you can temporarily change your pubspec.yaml file to:

  audio_service:
    git:
      url: https://github.com/ryanheise/audio_service.git

Note that git master is not stable and should not be used in production.

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