Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Vendor audio_service to fix iOS playbackState ifdef on pause

Barnabas79e9c7b5b2c9
diff --git a/packages/audio_service/CHANGELOG.md b/packages/audio_service/CHANGELOG.md
new file mode 100644
index 00000000..658f8fcb
--- /dev/null
+++ b/packages/audio_service/CHANGELOG.md
@@ -0,0 +1,442 @@
+## 0.18.18
+
+* Fix setPlaybackState entitlement issue on iOS.
+* Fix Android stopForeground deprecation warning.
+* Bump compile/target SDK to 35 on Android.
+* Bump minSdk to 19 on Android.
+* bump AGP to 8.5.2.
+
+## 0.18.17
+
+* Add support for SwiftPM.
+
+## 0.18.16
+
+* Support MPNowPlayingInfoPropertyIsLiveStream on IOS (@MuradSh, @celsoft).
+
+## 0.18.15
+
+* Add deep link support for FlutterFragmentActivity (@jan-milovanovic).
+* Fix JDK 21 compile error.
+
+## 0.18.14
+
+* Support rxdart 0.28.x.
+
+## 0.18.13
+
+* Fix Android NPE in sendNotificationClicked and onConnected.
+* Catch and broadcast async platform exceptions.
+* Support js '>=0.6.3 <0.8.0'
+* Fix setAndroidPlaybackInfo call blocking (@julianscheel).
+* Pass through missing extras to playFrom.../prepareFrom... (@Ruchit2759).
+
+## 0.18.12
+
+* Fix crash with Oppo/OnePlus devices running Android 13.
+
+## 0.18.11
+
+* Support custom media controls (@defsub)
+* Support fast forward, rewind and stop when targeting Android 13 (@defsub)
+
+## 0.18.10
+
+* Add support for AGP 8 (@theskyblockman).
+* Update AGP to 7.3.0.
+* Update minimum flutter version to 3.0.
+
+## 0.18.9
+
+* Fix cache bug in AudioServiceFragmentActivity (@Mordtimer).
+* Add Android Auto manifest entry for example app (@ColinSchmale).
+
+## 0.18.8
+
+* Improve efficiency of mediaItem updates (@nt4f04uNd).
+
+## 0.18.7
+
+* Fix stopForeground bug on Android SDK < 24.
+* Migrate to androidx.media 1.6.0 (@snipd-mikel)
+* Propagate MediaItem extras to Android Auto (@snipd-mikel)
+* Update progress bar in Android Auto (@snipd-mikel)
+
+## 0.18.6
+
+* Fix build when targeting Android 13.
+* Add MediaItem.artHeaders.
+
+## 0.18.5
+
+* Add AudioServiceFragmentActivity (@deimantasa).
+* Support `content://` art URIs in notification on Android (@nt4f04uNd).
+* Document Android foregroundServiceType.
+
+## 0.18.4
+
+* Fix Android FlutterJNI error after quick relaunch.
+* Fix Android NPE when destroying additional FlutterEngines.
+
+## 0.18.3
+
+* Fix build when targeting Android 12.
+
+## 0.18.2
+
+* Guard against NPE when Android service is destroyed quickly.
+* Migrate to flutter_lints.
+* Queue messages from platform if init() called late.
+* Fix deep linking on Android (@vishna/@ryanheise).
+
+## 0.18.1
+
+* Remove iOS notification on stop.
+* Fix setSpeed action on iOS.
+* Eliminate redundant notification updates on Android.
+* Handle null album and artist on web (@nt4f04uNd).
+* Fix multithreaded crash in notification tap (@nt4f04uNd).
+* Fix regression to show album art on lock screen (@nt4f04uNd).
+* Add playlist/shuffle/loop example.
+
+## 0.18.0
+
+* Use a single isolate for easier communication.
+* Replace BackgroundAudioTask by AudioHandler.
+* Replace AudioService.start by AudioService.init.
+* Android Auto support.
+* Android 11 media session resumption support.
+* Federated plugin model.
+* Composable audio handlers (@yringler).
+* More callbacks:
+ * prepareFromSearch
+ * prepareFromUri
+ * playFromSearch
+ * playFromUri
+ * addQueueItems
+ * removeQueueItemAt
+ * setCaptioningEnabled
+ * getMediaItem
+ * search
+ * androidSetRemoteVolume
+ * androidAdjustRemoteVolume
+* More state:
+ * queueTitle
+ * ratingStyle
+ * androidPlaybackInfo
+ * customState
+* Default platform implementation for Windows/Linux (@keaganhilliard)
+* iOS/macOS control center bug fixes (@nt4f04uNd)
+* Fix queue index out of bounds bug (@kcrebound)
+* Fix bug when starting foreground service from background (@chengyuhui)
+* Make MediaItem.album nullable (@letiagoalves)
+* Code quality:
+ * Unit tests (@suragch, @nt4f04uNd)
+ * Strong-mode and pedantic lints, code consistency (@nt4f04uNd)
+* Improve artUri performance on Android (@nt4f04uNd)
+* Better detection of browser support (@nt4f04uNd)
+
+## 0.17.1
+
+* Support rxdart 0.27.0.
+
+## 0.17.0
+
+* Null safety.
+* Change artUri type from String to Uri.
+
+## 0.16.2+1
+
+* Mention upcoming 0.18.0 release in README.
+
+## 0.16.2
+
+* Fix positionStream bug when seek is interrupted by onStop.
+* Fix JS name clash for MediaMetadata.
+* Update NowPlayingInfo speed correctly on iOS (@ryotayama).
+
+## 0.16.1
+
+* Fix bug in start() when using HttpOverrides.
+
+## 0.16.0
+
+* setState parameters default to previous state.
+* Change updateTime from Duration to DateTime.
+* Rename newStartRating to newStarRating.
+* Declare type of MediaItem.extras (@hacker1024).
+* Unit tests.
+* Fix compile error on macOS.
+* Update dependencies.
+
+## 0.15.3
+
+* Add positionStream and runningStream.
+* Add androidShowNotificationBadge option (@aleexbt).
+
+## 0.15.2
+
+* Process connect/disconnect/start requests in a queue.
+* Guard against null setState arguments.
+* Range check in onSkipToPrevious (@snaeji).
+
+## 0.15.1
+
+* Fix loading of file:// artUri values.
+* Allow booleans/doubles in MediaItems.
+* Silently ignore duplicate onStop requests.
+
+## 0.15.0
+
+* Web support (@keaganhilliard)
+* macOS support (@hacker1024)
+* Route next/previous buttons to onClick on Android (@stonega)
+* Correctly scale skip intervals for control center (@subhash279)
+* Handle repeated stop/start calls more robustly.
+* Fix Android 11 bugs.
+
+## 0.14.1
+
+* audio_session dependency now supports minSdkVersion 16 on Android.
+
+## 0.14.0
+
+* audio session management now handled by audio_session (see [Migration Guide](https://github.com/ryanheise/audio_service/wiki/Migration-Guide#0140)).
+* Exceptions in background audio task are logged and forwarded to client.
+
+## 0.13.0
+
+* All BackgroundAudioTask callbacks are now async.
+* Add default implementation of onSkipToNext/onSkipToPrevious.
+* Bug fixes.
+
+## 0.12.0
+
+* Add setRepeatMode/setShuffleMode.
+* Enable iOS Control Center buttons based on setState.
+* Support seek forward/backward in iOS Control Center.
+* Add default behaviour to BackgroundAudioTask.
+* Bug fixes.
+* Simplify example.
+
+## 0.11.2
+
+* Fix bug with album metadata on Android.
+
+## 0.11.1
+
+* Allow setting the iOS audio session category and options.
+* Allow AudioServiceWidget to recognise swipe gesture on iOS.
+* Check for null title and album on Android.
+
+## 0.11.0
+
+* Breaking change: onStop must await super.onStop to shutdown task.
+* Fix Android memory leak.
+
+## 0.10.0
+
+* Replace androidStopOnRemoveTask with onTaskRemoved callback.
+* Add onClose callback.
+* Breaking change: new MediaButtonReceiver in AndroidManifest.xml.
+
+## 0.9.0
+
+* New state model: split into playing + processingState.
+* androidStopForegroundOnPause ties foreground state to playing state.
+* Add MediaItem.toJson/fromJson.
+* Add AudioService.notificationClickEventStream (Android).
+* Add AudioService.updateMediaItem.
+* Add AudioService.setSpeed.
+* Add PlaybackState.bufferedPosition.
+* Add custom AudioService.start parameters.
+* Rename replaceQueue -> updateQueue.
+* Rename Android-specific start parameters with android- prefix.
+* Use Duration type for all time values.
+* Pass fastForward/rewind intervals through to background task.
+* Allow connections from background contexts (e.g. android_alarm_manager).
+* Unify iOS/Android focus APIs.
+* Bug fixes and dependency updates.
+
+## 0.8.0
+
+* Allow UI to await the result of custom actions.
+* Allow background to broadcast custom events to UI.
+* Improve memory management for art bitmaps on Android.
+* Convenience methods: replaceQueue, playMediaItem, addQueueItems.
+* Bug fixes and dependency updates.
+
+## 0.7.2
+
+* Shutdown background task if task killed by IO (Android).
+* Bug fixes and dependency updates.
+
+## 0.7.1
+
+* Add AudioServiceWidget to auto-manage connections.
+* Allow file URIs for artUri.
+
+## 0.7.0
+
+* Support skip forward/backward in command center (iOS).
+* Add 'extras' field to MediaItem.
+* Artwork caching and preloading supported on Android+iOS.
+* Bug fixes.
+
+## 0.6.2
+
+* Bug fixes.
+
+## 0.6.1
+
+* Option to stop service on closing task (Android).
+
+## 0.6.0
+
+* Migrated to V2 embedding API (Flutter 1.12).
+
+## 0.5.7
+
+* Destroy isolates after use.
+
+## 0.5.6
+
+* Support Flutter 1.12.
+
+## 0.5.5
+
+* Bump sdk version to 2.6.0.
+
+## 0.5.4
+
+* Fix Android memory leak.
+
+## 0.5.3
+
+* Support Queue, album art and other missing features on iOS.
+
+## 0.5.2
+
+* Update documentation and example.
+
+## 0.5.1
+
+* Playback state broadcast on connect (iOS).
+
+## 0.5.0
+
+* Partial iOS support.
+
+## 0.4.2
+
+* Option to call stopForeground on pause.
+
+## 0.4.1
+
+* Fix queue support bug
+
+## 0.4.0
+
+* Breaking change: AudioServiceBackground.run takes a single parameter.
+
+## 0.3.1
+
+* Update example to disconnect when pressing back button.
+
+## 0.3.0
+
+* Breaking change: updateTime now measured since epoch instead of boot time.
+
+## 0.2.1
+
+* Streams use RxDart BehaviorSubject.
+
+## 0.2.0
+
+* Migrate to AndroidX.
+
+## 0.1.1
+
+* Bump targetSdkVersion to 28
+* Clear client-side metadata and state on stop.
+
+## 0.1.0
+
+* onClick is now always called for media button clicks.
+* Option to set notifications as ongoing.
+
+## 0.0.15
+
+* Option to set subText in notification.
+* Support media item ratings
+
+## 0.0.14
+
+* Can update existing media items.
+* Can specify order of Android notification compact actions.
+* Bug fix with connect.
+
+## 0.0.13
+
+* Option to preload artwork.
+* Allow client to browse media items.
+
+## 0.0.12
+
+* More options to customise the notification content.
+
+## 0.0.11
+
+* Breaking API changes.
+* Connection callbacks replaced by a streams API.
+* AudioService properties for playbackState, currentMediaItem, queue.
+* Option to set Android notification channel description.
+* AudioService.customAction awaits completion of the action.
+
+## 0.0.10
+
+* Bug fixes with queue management.
+* AudioService.start completes when the background task is ready.
+
+## 0.0.9
+
+* Support queue management.
+
+## 0.0.8
+
+* Bug fix.
+
+## 0.0.7
+
+* onMediaChanged takes MediaItem parameter.
+* Support playFromMediaId, fastForward, rewind.
+
+## 0.0.6
+
+* All APIs address media items by String mediaId.
+
+## 0.0.5
+
+* Show media art in notification and lock screen.
+
+## 0.0.4
+
+* Support and example for playing TextToSpeech.
+* Click notification to launch UI.
+* More properties added to MediaItem.
+* Minor API changes.
+
+## 0.0.3
+
+* Pause now keeps background isolate running
+* Notification channel id is generated from package name
+* Updated example to use audioplayer plugin
+* Fixed media button handling
+
+## 0.0.2
+
+* Better connection handling.
+
+## 0.0.1
+
+* Initial release.
diff --git a/packages/audio_service/LICENSE b/packages/audio_service/LICENSE
new file mode 100644
index 00000000..3bab693e
--- /dev/null
+++ b/packages/audio_service/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2018-2021 Ryan Heise and the project contributors.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/packages/audio_service/README.md b/packages/audio_service/README.md
new file mode 100644
index 00000000..8ca0cc1c
--- /dev/null
+++ b/packages/audio_service/README.md
@@ -0,0 +1,425 @@
+# audio_service
+
+This plugin wraps around your existing audio code to allow it to run in the background and interact with the media notification, the lock screen, headset buttons, wearables and Android Auto. It supports Android, iOS, web and Linux (via [audio_service_mpris](https://pub.dev/packages/audio_service_mpris)). 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 an audio handler which implements a set of standard system callbacks to handle media playback requests from different sources in a uniform way:
+
+![audio_handler](https://user-images.githubusercontent.com/19899190/100403242-762e7480-30b2-11eb-9fcf-938e08beee53.png)
+
+You implement these callbacks to play the particular type of audio that your app needs to play in response to these requests. For example, a Text-to-speech reader app might implement these callbacks using [flutter_tts](https://pub.dartlang.org/packages/flutter_tts) to render the speech, while a music player app might implement these callbacks using [just_audio](https://pub.dartlang.org/packages/just_audio) to render the audio.
+
+| Feature | Android | iOS | macOS | Web |
+| ------- | :-------: | :-----: | :-----: | :-----: |
+| background audio | ✅ | ✅ | ✅ | ✅ |
+| headset clicks | ✅ | ✅ | ✅ | ✅ |
+| play/pause/seek/rate/stop | ✅ | ✅ | ✅ | ✅ |
+| fast forward/rewind | ✅ | ✅ | ✅ | ✅ |
+| repeat/shuffle mode | ✅ | ✅ | ✅ | ✅ |
+| queue manipulation, skip next/prev | ✅ | ✅ | ✅ | ✅ |
+| custom actions/events/states | ✅ | ✅ | ✅ | ✅ |
+| notifications/control center | ✅ | ✅ | ✅ | ✅ |
+| lock screen controls | ✅ | ✅ | | ✅ |
+| album art | ✅ | ✅ | ✅ | ✅ |
+| Android Auto, Apple CarPlay | ✅ | ✅ | | |
+
+If you'd like to help with any missing features, please join us on the [GitHub issues page](https://github.com/ryanheise/audio_service/issues).
+
+## Tutorials and documentation
+
+* [Background audio in Flutter with Audio Service and Just Audio](https://suragch.medium.com/background-audio-in-flutter-with-audio-service-and-just-audio-3cce17b4a7d?sk=0837a1b1773e27a4f879ff3072e90305) by @suragch
+* [Tutorial](https://github.com/ryanheise/audio_service/wiki/Tutorial): walks you through building a simple audio player while explaining the basic concepts.
+* [Full example](https://github.com/ryanheise/audio_service): The `example` subdirectory on GitHub demonstrates both music and text-to-speech use cases.
+* [Frequently Asked Questions](https://github.com/ryanheise/audio_service/wiki/FAQ)
+* [API documentation](https://pub.dev/documentation/audio_service/latest/audio_service/audio_service-library.html)
+
+## Can I make use of other plugins within the audio handler?
+
+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](https://pub.dartlang.org/packages/just_audio), [flutter_tts](https://pub.dartlang.org/packages/flutter_tts), and others, within your audio handler. There are also plugins like [just_audio_handlers](https://github.com/yringler/inside-app/tree/master/just_audio_handlers) that provide default implementations of `AudioHandler` 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
+
+### Initialisation
+
+Define your `AudioHandler` with the callbacks that you want your app to handle:
+
+```dart
+class MyAudioHandler extends BaseAudioHandler
+ with QueueHandler, // mix in default queue callback implementations
+ SeekHandler { // mix in default seek callback implementations
+
+ final _player = AudioPlayer(); // e.g. just_audio
+
+ // The most common callbacks:
+ Future<void> play() => _player.play();
+ Future<void> pause() => _player.pause();
+ Future<void> stop() => _player.stop();
+ Future<void> seek(Duration position) => _player.seek(position);
+ Future<void> skipToQueueItem(int i) => _player.seek(Duration.zero, index: i);
+}
+```
+
+Register your `AudioHandler` during app startup:
+
+```dart
+Future<void> main() async {
+ // store this in a singleton
+ _audioHandler = await AudioService.init(
+ builder: () => MyAudioHandler(),
+ config: AudioServiceConfig(
+ androidNotificationChannelId: 'com.mycompany.myapp.channel.audio',
+ androidNotificationChannelName: 'Music playback',
+ ),
+ );
+ runApp(new MyApp());
+}
+```
+
+### Sending requests to the audio handler from Flutter
+
+Standard controls:
+
+```dart
+_audioHandler.play();
+_audioHandler.seek(Duration(seconds: 10));
+_audioHandler.setSpeed(1.5);
+_audioHandler.pause();
+_audioHandler.stop();
+```
+
+Playing specific media items:
+
+```dart
+var item = MediaItem(
+ id: 'https://example.com/audio.mp3',
+ album: 'Album name',
+ title: 'Track title',
+ artist: 'Artist name',
+ duration: const Duration(milliseconds: 123456),
+ artUri: Uri.parse('https://example.com/album.jpg'),
+);
+
+_audioHandler.playMediaItem(item);
+_audioHandler.playFromSearch(queryString);
+_audioHandler.playFromUri(uri);
+_audioHandler.playFromMediaId(id);
+```
+
+Queue management:
+
+```dart
+_audioHandler.addQueueItem(item);
+_audioHandler.insertQueueItem(1, item);
+_audioHandler.removeQueueItem(item);
+_audioHandler.updateQueue([item, ...]);
+_audioHandler.skipToNext();
+_audioHandler.skipToPrevious();
+_audioHandler.skipToQueueItem(2);
+```
+
+Looping and shuffling:
+
+```dart
+_audioHandler.setRepeatMode(AudioServiceRepeatMode.one); // none/one/all/group
+_audioHandler.setShuffleMode(AudioServiceShuffleMode.all); // none/all/group
+```
+
+Custom actions:
+
+```dart
+_audioHandler.customAction('setVolume', {'volume': 0.8});
+_audioHandler.customAction('saveBookmark');
+```
+
+### Broadcasting state changes
+
+Your audio handler must broadcast state changes so that the system notification and smart watches (etc) know what state to display. Your app's Flutter UI may also listen to these state changes so that it knows what state to display. Thus, the audio handler provides a single source of truth for your audio state to all clients.
+
+Broadcast the current media item:
+
+```dart
+class MyAudioHandler extends BaseAudioHandler ... {
+ ...
+ mediaItem.add(item1);
+ ...
+```
+
+Broadcast the current queue:
+
+```dart
+ ...
+ queue.add(<MediaItem>[item1, item2, item3]);
+ ...
+```
+
+Broadcast the current playback state:
+
+```dart
+ ...
+ // All options shown:
+ playbackState.add(PlaybackState(
+ // Which buttons should appear in the notification now
+ controls: [
+ MediaControl.skipToPrevious,
+ MediaControl.pause,
+ MediaControl.stop,
+ MediaControl.skipToNext,
+ ],
+ // Which other actions should be enabled in the notification
+ systemActions: const {
+ MediaAction.seek,
+ MediaAction.seekForward,
+ MediaAction.seekBackward,
+ },
+ // Which controls to show in Android's compact view.
+ androidCompactActionIndices: const [0, 1, 3],
+ // Whether audio is ready, buffering, ...
+ processingState: AudioProcessingState.ready,
+ // Whether audio is playing
+ playing: true,
+ // The current position as of this update. You should not broadcast
+ // position changes continuously because listeners will be able to
+ // project the current position after any elapsed time based on the
+ // current speed and whether audio is playing and ready. Instead, only
+ // broadcast position updates when they are different from expected (e.g.
+ // buffering, or seeking).
+ updatePosition: Duration(milliseconds: 54321),
+ // The current buffered position as of this update
+ bufferedPosition: Duration(milliseconds: 65432),
+ // The current speed
+ speed: 1.0,
+ // The current queue position
+ queueIndex: 0,
+ ));
+```
+
+Broadcasting mutations of the current playback state using `copyWith`:
+
+```dart
+ playbackState.add(playbackState.value.copyWith(
+ // Keep all existing state the same with only the speed changed:
+ speed: newSpeed,
+ ));
+```
+
+### Listening to state changes
+
+Listen to changes to the currently playing item from the Flutter UI:
+
+```dart
+_audioHandler.mediaItem.listen((MediaItem item) { ... });
+```
+
+Listen to changes to the queue from the Flutter UI:
+
+```dart
+_audioHandler.queue.listen((List<MediaItem> queue) { ... });
+```
+
+Listen to playback state changes from the Flutter UI:
+
+```dart
+_audioHandler.playbackState.listen((PlaybackState state) {
+ if (state.playing) ... else ...
+ switch (state.processingState) {
+ case AudioProcessingState.idle: ...
+ case AudioProcessingState.loading: ...
+ case AudioProcessingState.buffering: ...
+ case AudioProcessingState.ready: ...
+ case AudioProcessingState.completed: ...
+ case AudioProcessingState.error: ...
+ }
+});
+```
+
+Listen to a stream of continuous changes to the current playback position:
+
+```dart
+AudioService.position.listen((Duration position) { ... });
+```
+
+### Advanced features
+
+Compose multiple audio handler classes:
+
+```dart
+_audioHandler = await AudioService.init(
+ builder: () => AnalyticsAudioHandler(
+ PersistingAudioHandler(
+ MyAudioHandler())),
+);
+```
+
+Connecting from another isolate:
+
+```dart
+// Wrap audio handler in IsolatedAudioHandler:
+_audioHandler = await AudioService.init(
+ builder: () => IsolatedAudioHandler(
+ MyAudioHandler(),
+ portName: 'my_audio_handler',
+ ),
+);
+// From another isolate, obtain a proxy reference:
+_proxyAudioHandler = await IsolatedAudioHandler.lookup(
+ portName: 'my_audio_handler',
+);
+```
+
+See the full example for how to handle queues/playlists, headset button clicks, media artwork and text to speech.
+
+## 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](https://pub.dev/packages/audio_session) package to change the default audio session configuration for your app. E.g. for a podcast player, you may use:
+
+```dart
+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:
+
+```dart
+// 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](https://pub.dev/packages/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
+
+1. Make the following changes to your project's `AndroidManifest.xml` file:
+
+```xml
+<manifest xmlns:tools="http://schemas.android.com/tools" ...>
+ <!-- ADD THESE TWO PERMISSIONS -->
+ <uses-permission android:name="android.permission.WAKE_LOCK"/>
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
+ <!-- ALSO ADD THIS PERMISSION IF TARGETING SDK 34 -->
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"/>
+
+ <application ...>
+
+ ...
+
+ <!-- EDIT THE android:name ATTRIBUTE IN YOUR EXISTING "ACTIVITY" ELEMENT -->
+ <activity android:name="com.ryanheise.audioservice.AudioServiceActivity" ...>
+ ...
+ </activity>
+
+ <!-- ADD THIS "SERVICE" element -->
+ <service android:name="com.ryanheise.audioservice.AudioService"
+ android:foregroundServiceType="mediaPlayback"
+ android:exported="true" tools:ignore="Instantiatable">
+ <intent-filter>
+ <action android:name="android.media.browse.MediaBrowserService" />
+ </intent-filter>
+ </service>
+
+ <!-- ADD THIS "RECEIVER" element -->
+ <receiver android:name="com.ryanheise.audioservice.MediaButtonReceiver"
+ android:exported="true" tools:ignore="Instantiatable">
+ <intent-filter>
+ <action android:name="android.intent.action.MEDIA_BUTTON" />
+ </intent-filter>
+ </receiver>
+ </application>
+</manifest>
+```
+
+Note: As of Android 12, an app must have permission to restart a foreground service in the background, otherwise a `ForegroundServiceStartNotAllowedException` will be thrown. To avoid such an exception, you can either set `androidStopForegroundOnPause` to `false` in your `AudioServiceConfig` which keeps the service in the foreground during a pause so that restarting the foreground service is unnecessary, or you can keep the default `androidStopForegroundOnPause` setting of `true` (in line with best practices) and request the user to turn of battery optimisation for your app via the [optimize_battery](https://pub.dev/packages/optimize_battery) package. For more information, read [this page](https://developer.android.com/training/monitoring-device-state/doze-standby#support_for_other_use_cases).
+
+2. If you use any custom icons in notification, create the file `android/app/src/main/res/raw/keep.xml` to prevent them from being stripped during the build process:
+
+```xml
+<?xml version="1.0" encoding="utf-8"?>
+<resources xmlns:tools="http://schemas.android.com/tools"
+ tools:keep="@drawable/*" />
+```
+
+By default plugin's default icons are not stripped by R8. If you don't use them, you may selectively strip them. For example, the rules below will keep all your icons and discard all the plugin's:
+
+```xml
+<?xml version="1.0" encoding="utf-8"?>
+<resources xmlns:tools="http://schemas.android.com/tools"
+ tools:keep="@drawable/*"
+ tools:discard="@drawable/audio_service_*"
+/>
+```
+
+For more information about shrinking see [Android documentation](https://developer.android.com/studio/build/shrink-code#keep-resources).
+
+
+### Custom Android activity
+
+If your app needs to use its own custom activity, make sure you update your `AndroidManifest.xml` file to reference your activity's class name instead of `AudioServiceActivity`. For example, if your activity class is named `MainActivity`, then use:
+
+```xml
+ <activity android:name=".MainActivity" ...>
+```
+
+Depending on whether you activity is a regular `Activity` or a `FragmentActivity`, you must also include some code to link to audio_service's shared `FlutterEngine`. The easiest way to accomplish this is to inherit that code from one of audio_service's provided base classes.
+
+1. Integration as an `Activity`:
+
+```java
+import com.ryanheise.audioservice.AudioServiceActivity;
+
+class MainActivity extends AudioServiceActivity {
+ // ...
+}
+```
+
+2. Integration as a `FragmentActivity`:
+
+```java
+import com.ryanheise.audioservice.AudioServiceFragmentActivity;
+
+class MainActivity extends AudioServiceFragmentActivity {
+ // ...
+}
+```
+
+You can also write your own activity class from scratch, and override the `provideFlutterEngine`, `getCachedEngineId` and `shouldDestroyEngineWithHost` methods yourself. For inspiration, see the source code of the provided `AudioServiceActivity` and `AudioServiceFragmentActivity` classes.
+
+## 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.
+
+Note that the `audio` background mode permits an app to run in the background only for the purpose of playing audio. The OS may kill your process if it sits idly without playing audio, for example, by using a timer to sleep for a few seconds. If your app needs to pause for a few seconds between audio tracks, consider playing a silent audio track to create that effect rather than using an idle timer.
+
+## 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'
+```
diff --git a/packages/audio_service/analysis_options.yaml b/packages/audio_service/analysis_options.yaml
new file mode 100644
index 00000000..c410b6d7
--- /dev/null
+++ b/packages/audio_service/analysis_options.yaml
@@ -0,0 +1,13 @@
+include: package:flutter_lints/flutter.yaml
+
+analyzer:
+ language:
+ strict-casts: true
+ strict-inference: true
+ strict-raw-types: true
+
+linter:
+ rules:
+ prefer_single_quotes: false
+ unawaited_futures: false
+ public_member_api_docs: true
diff --git a/packages/audio_service/android/build.gradle b/packages/audio_service/android/build.gradle
new file mode 100644
index 00000000..86bd5167
--- /dev/null
+++ b/packages/audio_service/android/build.gradle
@@ -0,0 +1,51 @@
+group = "com.ryanheise.audioservice"
+version "1.0-SNAPSHOT"
+def args = ["-Xlint:deprecation","-Xlint:unchecked"]
+
+buildscript {
+ ext {
+ agp_version = '8.5.2'
+ }
+ repositories {
+ google()
+ mavenCentral()
+ }
+
+ dependencies {
+ classpath "com.android.tools.build:gradle:$agp_version"
+ }
+}
+
+rootProject.allprojects {
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+
+project.getTasks().withType(JavaCompile) {
+ options.compilerArgs.addAll(args)
+}
+
+apply plugin: "com.android.library"
+
+android {
+ namespace "com.ryanheise.audioservice"
+ compileSdk = 35
+
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_11
+ targetCompatibility = JavaVersion.VERSION_11
+ }
+ defaultConfig {
+ minSdk = 19
+ }
+ lintOptions {
+ disable 'InvalidPackage'
+ }
+}
+
+dependencies {
+ implementation 'androidx.media:media:1.7.0'
+ implementation 'androidx.core:core:1.13.1'
+}
diff --git a/packages/audio_service/android/gradle.properties b/packages/audio_service/android/gradle.properties
new file mode 100644
index 00000000..38c8d454
--- /dev/null
+++ b/packages/audio_service/android/gradle.properties
@@ -0,0 +1,4 @@
+org.gradle.jvmargs=-Xmx1536M
+android.enableR8=true
+android.useAndroidX=true
+android.enableJetifier=true
diff --git a/packages/audio_service/android/gradle/wrapper/gradle-wrapper.properties b/packages/audio_service/android/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 00000000..48c0a02c
--- /dev/null
+++ b/packages/audio_service/android/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,5 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/packages/audio_service/android/settings.gradle b/packages/audio_service/android/settings.gradle
new file mode 100644
index 00000000..8fa78ff9
--- /dev/null
+++ b/packages/audio_service/android/settings.gradle
@@ -0,0 +1 @@
+rootProject.name = 'audio_service'
diff --git a/packages/audio_service/android/src/main/AndroidManifest.xml b/packages/audio_service/android/src/main/AndroidManifest.xml
new file mode 100644
index 00000000..a2f47b60
--- /dev/null
+++ b/packages/audio_service/android/src/main/AndroidManifest.xml
@@ -0,0 +1,2 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+</manifest>
diff --git a/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioProcessingState.java b/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioProcessingState.java
new file mode 100644
index 00000000..d083855c
--- /dev/null
+++ b/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioProcessingState.java
@@ -0,0 +1,10 @@
+package com.ryanheise.audioservice;
+
+public enum AudioProcessingState {
+ idle,
+ loading,
+ buffering,
+ ready,
+ completed,
+ error,
+}
diff --git a/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioService.java b/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioService.java
new file mode 100644
index 00000000..a4afa375
--- /dev/null
+++ b/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioService.java
@@ -0,0 +1,1155 @@
+package com.ryanheise.audioservice;
+
+import android.app.Notification;
+import android.app.NotificationChannel;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.media.AudioManager;
+import android.net.Uri;
+import android.os.Build;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.ParcelFileDescriptor;
+import android.os.PowerManager;
+import android.support.v4.media.MediaBrowserCompat;
+import android.support.v4.media.MediaDescriptionCompat;
+import android.support.v4.media.MediaMetadataCompat;
+import android.support.v4.media.RatingCompat;
+import android.support.v4.media.session.MediaControllerCompat;
+import android.support.v4.media.session.MediaSessionCompat;
+import android.support.v4.media.session.PlaybackStateCompat;
+import android.util.LruCache;
+import android.util.Size;
+import android.view.KeyEvent;
+
+import androidx.annotation.RequiresApi;
+import androidx.core.app.ServiceCompat;
+import androidx.core.content.ContextCompat;
+import androidx.core.app.NotificationCompat;
+import androidx.media.MediaBrowserServiceCompat;
+import androidx.media.VolumeProviderCompat;
+import androidx.media.app.NotificationCompat.MediaStyle;
+import androidx.media.utils.MediaConstants;
+
+import java.io.FileDescriptor;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import io.flutter.embedding.engine.FlutterEngine;
+
+public class AudioService extends MediaBrowserServiceCompat {
+ public static final String CONTENT_STYLE_SUPPORTED = "android.media.browse.CONTENT_STYLE_SUPPORTED";
+ public static final String CONTENT_STYLE_PLAYABLE_HINT = "android.media.browse.CONTENT_STYLE_PLAYABLE_HINT";
+ public static final String CONTENT_STYLE_BROWSABLE_HINT = "android.media.browse.CONTENT_STYLE_BROWSABLE_HINT";
+ public static final int CONTENT_STYLE_LIST_ITEM_HINT_VALUE = 1;
+ public static final int CONTENT_STYLE_GRID_ITEM_HINT_VALUE = 2;
+ public static final int CONTENT_STYLE_CATEGORY_LIST_ITEM_HINT_VALUE = 3;
+ public static final int CONTENT_STYLE_CATEGORY_GRID_ITEM_HINT_VALUE = 4;
+
+ private static final String SHARED_PREFERENCES_NAME = "audio_service_preferences";
+
+ private static final int NOTIFICATION_ID = 1124;
+ private static final int REQUEST_CONTENT_INTENT = 1000;
+ public static final String NOTIFICATION_CLICK_ACTION = "com.ryanheise.audioservice.NOTIFICATION_CLICK";
+ public static final String CUSTOM_ACTION_STOP = "com.ryanheise.audioservice.action.STOP";
+ public static final String CUSTOM_ACTION_FAST_FORWARD = "com.ryanheise.audioservice.action.FAST_FORWARD";
+ public static final String CUSTOM_ACTION_REWIND = "com.ryanheise.audioservice.action.REWIND";
+ private static final String BROWSABLE_ROOT_ID = "root";
+ private static final String RECENT_ROOT_ID = "recent";
+ // See the comment in onMediaButtonEvent to understand how the BYPASS keycodes work.
+ // We hijack KEYCODE_MUTE and KEYCODE_MEDIA_RECORD since the media session subsystem
+ // considers these keycodes relevant to media playback and will pass them on to us.
+ public static final int KEYCODE_BYPASS_PLAY = KeyEvent.KEYCODE_MUTE;
+ public static final int KEYCODE_BYPASS_PAUSE = KeyEvent.KEYCODE_MEDIA_RECORD;
+ public static final int MAX_COMPACT_ACTIONS = 3;
+ private static final long AUTO_ENABLED_ACTIONS = PlaybackStateCompat.ACTION_STOP
+ | PlaybackStateCompat.ACTION_PAUSE
+ | PlaybackStateCompat.ACTION_PLAY
+ | PlaybackStateCompat.ACTION_REWIND
+ // Auto-enabling these is bad for Android Auto since it forces the
+ // previous/next buttons to always show.
+ //| PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS
+ //| PlaybackStateCompat.ACTION_SKIP_TO_NEXT
+ | PlaybackStateCompat.ACTION_FAST_FORWARD
+ | PlaybackStateCompat.ACTION_SET_RATING
+ // "seek" is the exception because it's the only action that
+ // affects the appearance of the media notification, so we leave it
+ // up to the plugin user whether to enable it (via systemActions).
+ //| PlaybackStateCompat.ACTION_SEEK_TO
+ | PlaybackStateCompat.ACTION_PLAY_PAUSE
+ | PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID
+ | PlaybackStateCompat.ACTION_PLAY_FROM_SEARCH
+ | PlaybackStateCompat.ACTION_SKIP_TO_QUEUE_ITEM
+ | PlaybackStateCompat.ACTION_PLAY_FROM_URI
+ | PlaybackStateCompat.ACTION_PREPARE
+ | PlaybackStateCompat.ACTION_PREPARE_FROM_MEDIA_ID
+ | PlaybackStateCompat.ACTION_PREPARE_FROM_SEARCH
+ | PlaybackStateCompat.ACTION_PREPARE_FROM_URI
+ | PlaybackStateCompat.ACTION_SET_REPEAT_MODE
+ | PlaybackStateCompat.ACTION_SET_SHUFFLE_MODE
+ | PlaybackStateCompat.ACTION_SET_CAPTIONING_ENABLED;
+
+ static AudioService instance;
+ private static PendingIntent contentIntent;
+ private static ServiceListener listener;
+ private static List<MediaSessionCompat.QueueItem> queue = new ArrayList<>();
+ private static final Map<String, MediaMetadataCompat> mediaMetadataCache = new HashMap<>();
+
+ public static void init(ServiceListener listener) {
+ AudioService.listener = listener;
+ }
+
+ public static int toKeyCode(long action) {
+ if (action == PlaybackStateCompat.ACTION_PLAY) {
+ return KEYCODE_BYPASS_PLAY;
+ } else if (action == PlaybackStateCompat.ACTION_PAUSE) {
+ return KEYCODE_BYPASS_PAUSE;
+ } else {
+ return PlaybackStateCompat.toKeyCode(action);
+ }
+ }
+
+ MediaMetadataCompat createMediaMetadata(String mediaId, String title, String album, String artist, String genre, Long duration, String artUri, Boolean playable, String displayTitle, String displaySubtitle, String displayDescription, RatingCompat rating, Map<?, ?> extras) {
+ MediaMetadataCompat.Builder builder = new MediaMetadataCompat.Builder()
+ .putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, mediaId)
+ .putString(MediaMetadataCompat.METADATA_KEY_TITLE, title);
+ if (album != null)
+ builder.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, album);
+ if (artist != null)
+ builder.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, artist);
+ if (genre != null)
+ builder.putString(MediaMetadataCompat.METADATA_KEY_GENRE, genre);
+ if (duration != null)
+ builder.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, duration);
+ if (artUri != null) {
+ builder.putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON_URI, artUri);
+ }
+ if (playable != null)
+ builder.putLong("playable_long", playable ? 1 : 0);
+ if (displayTitle != null)
+ builder.putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE, displayTitle);
+ if (displaySubtitle != null)
+ builder.putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_SUBTITLE, displaySubtitle);
+ if (displayDescription != null)
+ builder.putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_DESCRIPTION, displayDescription);
+ if (rating != null) {
+ builder.putRating(MediaMetadataCompat.METADATA_KEY_RATING, rating);
+ }
+ if (extras != null) {
+ for (Object o : extras.keySet()) {
+ String key = (String)o;
+ Object value = extras.get(key);
+ if (value instanceof Long) {
+ builder.putLong(key, (Long)value);
+ } else if (value instanceof Integer) {
+ builder.putLong(key, (long)((Integer)value));
+ } else if (value instanceof String) {
+ builder.putString(key, (String)value);
+ } else if (value instanceof Boolean) {
+ builder.putLong(key, (Boolean)value ? 1 : 0);
+ } else if (value instanceof Double) {
+ builder.putString(key, value.toString());
+ }
+ }
+ }
+ MediaMetadataCompat mediaMetadata = builder.build();
+ mediaMetadataCache.put(mediaId, mediaMetadata);
+ return mediaMetadata;
+ }
+
+ static MediaMetadataCompat getMediaMetadata(String mediaId) {
+ return mediaMetadataCache.get(mediaId);
+ }
+
+ Bitmap loadArtBitmap(String artUriString, String loadThumbnailUri) {
+ Bitmap bitmap = artBitmapCache.get(artUriString);
+ if (bitmap != null) return bitmap;
+ try {
+ // There are 3 cases handled by this function:
+ // 1. content URI with openFileDescriptor
+ // 2. content URI with loadThumbnail (when Android >= Q and specified by the config)
+ // 3. not content URI - loading from the file, or cache file created by the Dart side
+ Uri artUri = Uri.parse(artUriString);
+ boolean usesContentScheme = "content".equals(artUri.getScheme());
+ FileDescriptor fileDescriptor = null;
+ if (usesContentScheme) {
+ try {
+ if (loadThumbnailUri != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ Size defaultSize = new Size(192, 192);
+ bitmap = getContentResolver().loadThumbnail(
+ artUri,
+ new Size(config.artDownscaleWidth == -1
+ ? defaultSize.getWidth()
+ : config.artDownscaleWidth,
+ config.artDownscaleHeight == -1
+ ? defaultSize.getHeight()
+ : config.artDownscaleHeight),
+ null);
+ if (bitmap == null) {
+ return null;
+ }
+ } else {
+ ParcelFileDescriptor parcelFileDescriptor = getContentResolver().openFileDescriptor(artUri, "r");
+ if (parcelFileDescriptor != null) {
+ fileDescriptor = parcelFileDescriptor.getFileDescriptor();
+ } else {
+ return null;
+ }
+ }
+ } catch (FileNotFoundException ex) {
+ return null;
+ } catch (IOException ex) {
+ return null;
+ }
+ }
+ // Decode the image ourselves for scenarios 1 and 3 (see the comment above).
+ if (!usesContentScheme || fileDescriptor != null) {
+ if (config.artDownscaleWidth != -1) {
+ BitmapFactory.Options options = new BitmapFactory.Options();
+ options.inJustDecodeBounds = true;
+ if (fileDescriptor != null) {
+ BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
+ } else {
+ BitmapFactory.decodeFile(artUri.getPath(), options);
+ }
+ options.inSampleSize = calculateInSampleSize(options, config.artDownscaleWidth, config.artDownscaleHeight);
+ options.inJustDecodeBounds = false;
+
+ if (fileDescriptor != null) {
+ bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
+ } else {
+ bitmap = BitmapFactory.decodeFile(artUri.getPath(), options);
+ }
+ } else {
+ if (fileDescriptor != null) {
+ bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor);
+ } else {
+ bitmap = BitmapFactory.decodeFile(artUri.getPath());
+ }
+ }
+ }
+ artBitmapCache.put(artUriString, bitmap);
+ return bitmap;
+ } catch (Exception e) {
+ e.printStackTrace();
+ return null;
+ }
+ }
+
+ private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
+ final int height = options.outHeight;
+ final int width = options.outWidth;
+ int inSampleSize = 1;
+
+ if (height > reqHeight || width > reqWidth) {
+ final int halfHeight = height / 2;
+ final int halfWidth = width / 2;
+ while ((halfHeight / inSampleSize) >= reqHeight
+ && (halfWidth / inSampleSize) >= reqWidth) {
+ inSampleSize *= 2;
+ }
+ }
+
+ return inSampleSize;
+ }
+
+ private FlutterEngine flutterEngine;
+ private AudioServiceConfig config;
+ private PowerManager.WakeLock wakeLock;
+ private MediaSessionCompat mediaSession;
+ private MediaSessionCallback mediaSessionCallback;
+ private List<MediaControl> controls = new ArrayList<>();
+ private List<NotificationCompat.Action> nativeActions = new ArrayList<>();
+ private List<PlaybackStateCompat.CustomAction> customActions = new ArrayList<>();
+ private int[] compactActionIndices;
+ private MediaMetadataCompat mediaMetadata;
+ private Bitmap artBitmap;
+ private String notificationChannelId;
+ private LruCache<String, Bitmap> artBitmapCache;
+ private boolean playing = false;
+ private AudioProcessingState processingState = AudioProcessingState.idle;
+ private int repeatMode;
+ private int shuffleMode;
+ private boolean notificationCreated;
+ private final Handler handler = new Handler(Looper.getMainLooper());
+ private VolumeProviderCompat volumeProvider;
+
+ public AudioProcessingState getProcessingState() {
+ return processingState;
+ }
+
+ public boolean isPlaying() {
+ return playing;
+ }
+
+ public int getRepeatMode() {
+ return repeatMode;
+ }
+
+ public int getShuffleMode() {
+ return shuffleMode;
+ }
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ instance = this;
+ repeatMode = 0;
+ shuffleMode = 0;
+ notificationCreated = false;
+ playing = false;
+ processingState = AudioProcessingState.idle;
+ mediaSession = new MediaSessionCompat(this, "media-session");
+
+ configure(new AudioServiceConfig(getApplicationContext()));
+
+ mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_QUEUE_COMMANDS);
+ PlaybackStateCompat.Builder stateBuilder = new PlaybackStateCompat.Builder()
+ .setActions(AUTO_ENABLED_ACTIONS);
+ mediaSession.setPlaybackState(stateBuilder.build());
+ mediaSession.setCallback(mediaSessionCallback = new MediaSessionCallback());
+ setSessionToken(mediaSession.getSessionToken());
+ mediaSession.setQueue(queue);
+
+ PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
+ wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, AudioService.class.getName());
+
+ // Get max available VM memory, exceeding this amount will throw an
+ // OutOfMemory exception. Stored in kilobytes as LruCache takes an
+ // int in its constructor.
+ final int maxMemory = (int)(Runtime.getRuntime().maxMemory() / 1024);
+
+ // Use 1/8th of the available memory for this memory cache.
+ final int cacheSize = maxMemory / 8;
+
+ artBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
+ @Override
+ protected int sizeOf(String key, Bitmap bitmap) {
+ // The cache size will be measured in kilobytes rather than
+ // number of items.
+ return bitmap.getByteCount() / 1024;
+ }
+ };
+
+ flutterEngine = AudioServicePlugin.getFlutterEngine(this);
+ System.out.println("flutterEngine warmed up");
+ }
+
+ @Override
+ public int onStartCommand(final Intent intent, int flags, int startId) {
+ MediaButtonReceiver.handleIntent(mediaSession, intent);
+ return START_NOT_STICKY;
+ }
+
+ public void stop() {
+ deactivateMediaSession();
+ stopSelf();
+ }
+
+ @Override
+ public void onDestroy() {
+ super.onDestroy();
+ if (listener != null) {
+ listener.onDestroy();
+ listener = null;
+ }
+ mediaMetadata = null;
+ artBitmap = null;
+ queue.clear();
+ mediaMetadataCache.clear();
+ controls.clear();
+ artBitmapCache.evictAll();
+ compactActionIndices = null;
+ releaseMediaSession();
+ ServiceCompat.stopForeground(this, config.androidResumeOnClick ? STOP_FOREGROUND_DETACH : STOP_FOREGROUND_REMOVE);
+ // This still does not solve the Android 11 problem.
+ // if (notificationCreated) {
+ // NotificationManager notificationManager = getNotificationManager();
+ // notificationManager.cancel(NOTIFICATION_ID);
+ // }
+ releaseWakeLock();
+ instance = null;
+ notificationCreated = false;
+ }
+
+ public AudioServiceConfig getConfig() {
+ return config;
+ }
+
+ public void configure(AudioServiceConfig config) {
+ this.config = config;
+ notificationChannelId = (config.androidNotificationChannelId != null)
+ ? config.androidNotificationChannelId
+ : getApplication().getPackageName() + ".channel";
+
+ if (config.activityClassName != null) {
+ Context context = getApplicationContext();
+ Intent intent = new Intent((String)null);
+ intent.setComponent(new ComponentName(context, config.activityClassName));
+ //Intent intent = new Intent(context, config.activityClassName);
+ intent.setAction(NOTIFICATION_CLICK_ACTION);
+ int flags = PendingIntent.FLAG_UPDATE_CURRENT;
+ if (Build.VERSION.SDK_INT >= 23) {
+ flags |= PendingIntent.FLAG_IMMUTABLE;
+ }
+ contentIntent = PendingIntent.getActivity(context, REQUEST_CONTENT_INTENT, intent, flags);
+ } else {
+ contentIntent = null;
+ }
+ if (!config.androidResumeOnClick) {
+ mediaSession.setMediaButtonReceiver(null);
+ }
+ }
+
+ int getResourceId(String resource) {
+ String[] parts = resource.split("/");
+ String resourceType = parts[0];
+ String resourceName = parts[1];
+ return getResources().getIdentifier(resourceName, resourceType, getApplicationContext().getPackageName());
+ }
+
+ NotificationCompat.Action createAction(String resource, String label, long actionCode) {
+ int iconId = getResourceId(resource);
+ return new NotificationCompat.Action(iconId, label,
+ buildMediaButtonPendingIntent(actionCode));
+ }
+
+ private boolean needCustomMediaControl(MediaControl control) {
+ return control.customAction != null;
+ }
+
+ private Bundle mapToBundle(Map<?, ?> map) {
+ if (map == null) {
+ return null;
+ }
+ Bundle bundle = new Bundle();
+ for (Map.Entry<?, ?> entry : map.entrySet()) {
+ String key = entry.getKey().toString();
+ Object value = entry.getValue();
+ if (value instanceof Integer) {
+ bundle.putInt(key, (Integer)value);
+ } else if (value instanceof Long) {
+ bundle.putLong(key, (Long)value);
+ } else {
+ bundle.putString(key, value.toString());
+ }
+ }
+ return bundle;
+ }
+
+ PlaybackStateCompat.CustomAction createCustomAction(MediaControl control) {
+ int iconId = getResourceId(control.icon);
+ if (control.customAction != null) {
+ return new PlaybackStateCompat.CustomAction.Builder(control.customAction.name, control.label, iconId)
+ .setExtras(mapToBundle(control.customAction.extras))
+ .build();
+ } else if (Build.VERSION.SDK_INT >= 33) {
+ // Android 13 changes MediaControl behavior as documented here:
+ // https://developer.android.com/about/versions/13/behavior-changes-13
+ // The below actions will be added to slots 1-3, if included.
+ // 1 - ACTION_PLAY, ACTION_PLAY
+ // 2 - ACTION_SKIP_TO_PREVIOUS
+ // 3 - ACTION_SKIP_TO_NEXT
+ // Custom actions will use slots 2-5 if included.
+ // - ACTION_STOP
+ // - ACTION_FAST_FORWARD
+ // - ACTION_REWIND
+ if (control.actionCode == PlaybackStateCompat.ACTION_STOP) {
+ return new PlaybackStateCompat.CustomAction.Builder(CUSTOM_ACTION_STOP, control.label, iconId).build();
+ } else if (control.actionCode == PlaybackStateCompat.ACTION_FAST_FORWARD) {
+ return new PlaybackStateCompat.CustomAction.Builder(CUSTOM_ACTION_FAST_FORWARD, control.label, iconId).build();
+ } else if (control.actionCode == PlaybackStateCompat.ACTION_REWIND) {
+ return new PlaybackStateCompat.CustomAction.Builder(CUSTOM_ACTION_REWIND, control.label, iconId).build();
+ }
+ }
+ return null;
+ }
+
+ PendingIntent buildMediaButtonPendingIntent(long action) {
+ int keyCode = toKeyCode(action);
+ if (keyCode == KeyEvent.KEYCODE_UNKNOWN)
+ return null;
+ Intent intent = new Intent(this, MediaButtonReceiver.class);
+ intent.setAction(Intent.ACTION_MEDIA_BUTTON);
+ intent.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, keyCode));
+ int flags = 0;
+ if (Build.VERSION.SDK_INT >= 23) {
+ flags |= PendingIntent.FLAG_IMMUTABLE;
+ }
+ return PendingIntent.getBroadcast(this, keyCode, intent, flags);
+ }
+
+ PendingIntent buildDeletePendingIntent() {
+ Intent intent = new Intent(this, MediaButtonReceiver.class);
+ intent.setAction(MediaButtonReceiver.ACTION_NOTIFICATION_DELETE);
+ int flags = 0;
+ if (Build.VERSION.SDK_INT >= 23) {
+ flags |= PendingIntent.FLAG_IMMUTABLE;
+ }
+ return PendingIntent.getBroadcast(this, 0, intent, flags);
+ }
+
+ void setState(List<MediaControl> controls, long actionBits, int[] compactActionIndices, AudioProcessingState processingState, boolean playing, long position, long bufferedPosition, float speed, long updateTime, Integer errorCode, String errorMessage, int repeatMode, int shuffleMode, boolean captioningEnabled, Long queueIndex) {
+ boolean notificationChanged = false;
+ if (!Arrays.equals(compactActionIndices, this.compactActionIndices)) {
+ notificationChanged = true;
+ }
+ if (!controls.equals(this.controls)) {
+ notificationChanged = true;
+ }
+ this.controls = controls;
+ this.nativeActions.clear();
+ this.customActions.clear();
+ for (MediaControl control : controls) {
+ final PlaybackStateCompat.CustomAction customAction = createCustomAction(control);
+ if (customAction != null) {
+ customActions.add(customAction);
+ } else {
+ nativeActions.add(createAction(control.icon, control.label, control.actionCode));
+ }
+ }
+ this.compactActionIndices = compactActionIndices;
+ boolean wasPlaying = this.playing;
+ AudioProcessingState oldProcessingState = this.processingState;
+ this.processingState = processingState;
+ this.playing = playing;
+ this.repeatMode = repeatMode;
+ this.shuffleMode = shuffleMode;
+
+ PlaybackStateCompat.Builder stateBuilder = new PlaybackStateCompat.Builder()
+ .setActions(AUTO_ENABLED_ACTIONS | actionBits)
+ .setState(getPlaybackState(), position, speed, updateTime)
+ .setBufferedPosition(bufferedPosition);
+
+ for (PlaybackStateCompat.CustomAction action : this.customActions) {
+ stateBuilder.addCustomAction(action);
+ }
+
+ if (queueIndex != null)
+ stateBuilder.setActiveQueueItemId(queueIndex);
+ if (errorCode != null && errorMessage != null)
+ stateBuilder.setErrorMessage(errorCode, errorMessage);
+ else if (errorMessage != null)
+ stateBuilder.setErrorMessage(-987654, errorMessage);
+
+ if (mediaMetadata != null) {
+ // Update the progress bar in the browse view as content is playing as explained
+ // here: https://developer.android.com/training/cars/media#browse-progress-bar
+ Bundle extras = new Bundle();
+ extras.putString(MediaConstants.PLAYBACK_STATE_EXTRAS_KEY_MEDIA_ID, mediaMetadata.getDescription().getMediaId());
+ stateBuilder.setExtras(extras);
+ }
+
+ mediaSession.setPlaybackState(stateBuilder.build());
+ mediaSession.setRepeatMode(repeatMode);
+ mediaSession.setShuffleMode(shuffleMode);
+ mediaSession.setCaptioningEnabled(captioningEnabled);
+
+ if (!wasPlaying && playing) {
+ enterPlayingState();
+ } else if (wasPlaying && !playing) {
+ exitPlayingState();
+ }
+
+ if (oldProcessingState != AudioProcessingState.idle && processingState == AudioProcessingState.idle) {
+ // TODO: Handle completed state as well?
+ stop();
+ } else if (processingState != AudioProcessingState.idle && notificationChanged) {
+ updateNotification();
+ }
+ }
+
+ public void setPlaybackInfo(int playbackType, Integer volumeControlType, Integer maxVolume, Integer volume) {
+ if (playbackType == MediaControllerCompat.PlaybackInfo.PLAYBACK_TYPE_LOCAL) {
+ // We have to wait 'til media2 before we can use AudioAttributes.
+ mediaSession.setPlaybackToLocal(AudioManager.STREAM_MUSIC);
+ volumeProvider = null;
+ } else if (playbackType == MediaControllerCompat.PlaybackInfo.PLAYBACK_TYPE_REMOTE) {
+ if (volumeProvider == null || volumeControlType != volumeProvider.getVolumeControl() || maxVolume != volumeProvider.getMaxVolume()) {
+ volumeProvider = new VolumeProviderCompat(volumeControlType, maxVolume, volume) {
+ @Override
+ public void onSetVolumeTo(int volumeIndex) {
+ if (listener == null) return;
+ listener.onSetVolumeTo(volumeIndex);
+ }
+ @Override
+ public void onAdjustVolume(int direction) {
+ if (listener == null) return;
+ listener.onAdjustVolume(direction);
+ }
+ };
+ } else {
+ volumeProvider.setCurrentVolume(volume);
+ }
+ mediaSession.setPlaybackToRemote(volumeProvider);
+ } else {
+ // silently ignore
+ }
+ }
+
+ public int getPlaybackState() {
+ switch (processingState) {
+ case idle: return PlaybackStateCompat.STATE_NONE;
+ case loading: return PlaybackStateCompat.STATE_CONNECTING;
+ case buffering: return PlaybackStateCompat.STATE_BUFFERING;
+ case ready: return playing ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_PAUSED;
+ case completed: return playing ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_PAUSED;
+ case error: return PlaybackStateCompat.STATE_ERROR;
+ default: return PlaybackStateCompat.STATE_NONE;
+ }
+ }
+
+ private Notification buildNotification() {
+ int[] compactActionIndices = this.compactActionIndices;
+ if (compactActionIndices == null) {
+ compactActionIndices = new int[Math.min(MAX_COMPACT_ACTIONS, nativeActions.size())];
+ for (int i = 0; i < compactActionIndices.length; i++) compactActionIndices[i] = i;
+ }
+ NotificationCompat.Builder builder = getNotificationBuilder();
+ if (mediaMetadata != null) {
+ MediaDescriptionCompat description = mediaMetadata.getDescription();
+ if (description.getTitle() != null)
+ builder.setContentTitle(description.getTitle());
+ if (description.getSubtitle() != null)
+ builder.setContentText(description.getSubtitle());
+ if (description.getDescription() != null)
+ builder.setSubText(description.getDescription());
+ synchronized (this) {
+ if (artBitmap != null)
+ builder.setLargeIcon(artBitmap);
+ }
+ }
+ if (config.androidNotificationClickStartsActivity)
+ builder.setContentIntent(mediaSession.getController().getSessionActivity());
+ // TODO: Look at setColorized
+ if (config.notificationColor != -1)
+ builder.setColor(config.notificationColor);
+ for (NotificationCompat.Action action : nativeActions) {
+ builder.addAction(action);
+ }
+ final MediaStyle style = new MediaStyle()
+ .setMediaSession(mediaSession.getSessionToken());
+ if (Build.VERSION.SDK_INT < 33) {
+ style.setShowActionsInCompactView(compactActionIndices);
+ }
+ if (config.androidNotificationOngoing) {
+ style.setShowCancelButton(true);
+ style.setCancelButtonIntent(buildMediaButtonPendingIntent(PlaybackStateCompat.ACTION_STOP));
+ builder.setOngoing(true);
+ }
+ builder.setStyle(style);
+ return builder.build();
+ }
+
+ private NotificationManager getNotificationManager() {
+ return (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
+ }
+
+ private /*synchronized*/ NotificationCompat.Builder getNotificationBuilder() {
+ // This local variable could be commented out and replaced by an
+ // instance variable if we want to reuse the builder instance. However,
+ // there doesn't turn out to be much benefit to this since we don't
+ // actually reuse any of the previous notification values when setting
+ // a new notification.
+ NotificationCompat.Builder notificationBuilder = null;
+ if (notificationBuilder == null) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
+ createChannel();
+ notificationBuilder = new NotificationCompat.Builder(this, notificationChannelId)
+ .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
+ .setShowWhen(false)
+ .setDeleteIntent(buildDeletePendingIntent())
+ ;
+ }
+ int iconId = getResourceId(config.androidNotificationIcon);
+ notificationBuilder.setSmallIcon(iconId);
+ return notificationBuilder;
+ }
+
+ public void handleDeleteNotification() {
+ if (listener == null) return;
+ listener.onClose();
+ }
+
+
+ @RequiresApi(Build.VERSION_CODES.O)
+ private void createChannel() {
+ NotificationManager notificationManager = getNotificationManager();
+ NotificationChannel channel = notificationManager.getNotificationChannel(notificationChannelId);
+ if (channel == null) {
+ channel = new NotificationChannel(notificationChannelId, config.androidNotificationChannelName, NotificationManager.IMPORTANCE_LOW);
+ channel.setShowBadge(config.androidShowNotificationBadge);
+ if (config.androidNotificationChannelDescription != null)
+ channel.setDescription(config.androidNotificationChannelDescription);
+ notificationManager.createNotificationChannel(channel);
+ }
+ }
+
+ private void updateNotification() {
+ if (notificationCreated) {
+ getNotificationManager().notify(NOTIFICATION_ID, buildNotification());
+ }
+ }
+
+ private void enterPlayingState() {
+ ContextCompat.startForegroundService(this, new Intent(AudioService.this, AudioService.class));
+ if (!mediaSession.isActive())
+ mediaSession.setActive(true);
+
+ acquireWakeLock();
+ mediaSession.setSessionActivity(contentIntent);
+ internalStartForeground();
+ }
+
+ private void exitPlayingState() {
+ if (config.androidStopForegroundOnPause) {
+ exitForegroundState();
+ }
+ }
+
+ private void exitForegroundState() {
+ ServiceCompat.stopForeground(this, STOP_FOREGROUND_DETACH);
+ releaseWakeLock();
+ }
+
+ private void internalStartForeground() {
+ startForeground(NOTIFICATION_ID, buildNotification());
+ notificationCreated = true;
+ }
+
+ private void acquireWakeLock() {
+ if (!wakeLock.isHeld())
+ wakeLock.acquire();
+ }
+
+ private void releaseWakeLock() {
+ if (wakeLock.isHeld())
+ wakeLock.release();
+ }
+
+ private void activateMediaSession() {
+ if (!mediaSession.isActive())
+ mediaSession.setActive(true);
+ }
+
+ private void deactivateMediaSession() {
+ if (mediaSession.isActive()) {
+ mediaSession.setActive(false);
+ }
+ // Force cancellation of the notification
+ getNotificationManager().cancel(NOTIFICATION_ID);
+ }
+
+ private void releaseMediaSession() {
+ if (mediaSession == null) return;
+ deactivateMediaSession();
+ mediaSession.release();
+ mediaSession = null;
+ }
+
+ /**
+ * Updates queue.
+ * Gets called from background thread.
+ */
+ synchronized void setQueue(List<MediaSessionCompat.QueueItem> queue) {
+ AudioService.queue = queue;
+ mediaSession.setQueue(queue);
+ }
+
+ void playMediaItem(MediaDescriptionCompat description) {
+ mediaSessionCallback.onPlayMediaItem(description);
+ }
+
+ /**
+ * Updates metadata, loads the art and updates the notification.
+ * Gets called from background thread.
+ * <p>
+ * Also adds the loaded art bitmap to the MediaMetadata.
+ * This is needed to display art in lock screen in versions
+ * prior Android 11, in which this feature was removed.
+ * <p>
+ * See:
+ * - https://developer.android.com/guide/topics/media-apps/working-with-a-media-session#album_artwork
+ * - https://9to5google.com/2020/08/02/android-11-lockscreen-art/
+ */
+ synchronized void setMetadata(MediaMetadataCompat mediaMetadata) {
+ String artCacheFilePath = mediaMetadata.getString("artCacheFile");
+ if (artCacheFilePath != null) {
+ // Load local files and network images, cached in files
+ artBitmap = loadArtBitmap(artCacheFilePath, null);
+ mediaMetadata = putArtToMetadata(mediaMetadata);
+ } else {
+ // Load content:// URIs
+ String artUri = mediaMetadata.getString(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON_URI);
+ if (artUri != null && artUri.startsWith("content:")) {
+ String loadThumbnailUri = mediaMetadata.getString("loadThumbnailUri");
+ artBitmap = loadArtBitmap(artUri, loadThumbnailUri);
+ mediaMetadata = putArtToMetadata(mediaMetadata);
+ } else {
+ artBitmap = null;
+ }
+ }
+ this.mediaMetadata = mediaMetadata;
+ mediaSession.setMetadata(mediaMetadata);
+ handler.removeCallbacksAndMessages(null);
+ handler.post(this::updateNotification);
+ }
+
+ private MediaMetadataCompat putArtToMetadata(MediaMetadataCompat mediaMetadata) {
+ return new MediaMetadataCompat.Builder(mediaMetadata)
+ .putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, artBitmap)
+ .putBitmap(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON, artBitmap)
+ .build();
+ }
+
+ @Override
+ public BrowserRoot onGetRoot(String clientPackageName, int clientUid, Bundle rootHints) {
+ Boolean isRecentRequest = rootHints == null ? null : (Boolean)rootHints.getBoolean(BrowserRoot.EXTRA_RECENT);
+ if (isRecentRequest == null) isRecentRequest = false;
+ Bundle extras = config.getBrowsableRootExtras();
+ return new BrowserRoot(isRecentRequest ? RECENT_ROOT_ID : BROWSABLE_ROOT_ID, extras);
+ // The response must be given synchronously, and we can't get a
+ // synchronous response from the Dart layer. For now, we hardcode
+ // the root to "root". This may improve in media2.
+ //return listener.onGetRoot(clientPackageName, clientUid, rootHints);
+ }
+
+ @Override
+ public void onLoadChildren(final String parentMediaId, final Result<List<MediaBrowserCompat.MediaItem>> result) {
+ onLoadChildren(parentMediaId, result, null);
+ }
+
+ @Override
+ public void onLoadChildren(final String parentMediaId, final Result<List<MediaBrowserCompat.MediaItem>> result, Bundle options) {
+ if (listener == null) {
+ result.sendResult(new ArrayList<>());
+ return;
+ }
+ listener.onLoadChildren(parentMediaId, result, options);
+ }
+
+ @Override
+ public void onLoadItem(String itemId, Result<MediaBrowserCompat.MediaItem> result) {
+ if (listener == null) {
+ result.sendResult(null);
+ return;
+ }
+ listener.onLoadItem(itemId, result);
+ }
+
+ @Override
+ public void onSearch(String query, Bundle extras, Result<List<MediaBrowserCompat.MediaItem>> result) {
+ if (listener == null) {
+ result.sendResult(new ArrayList<>());
+ return;
+ }
+ listener.onSearch(query, extras, result);
+ }
+
+ @Override
+ public void onTaskRemoved(Intent rootIntent) {
+ if (listener != null) {
+ listener.onTaskRemoved();
+ }
+ super.onTaskRemoved(rootIntent);
+ }
+
+ public class MediaSessionCallback extends MediaSessionCompat.Callback {
+ @Override
+ public void onAddQueueItem(MediaDescriptionCompat description) {
+ if (listener == null) return;
+ listener.onAddQueueItem(getMediaMetadata(description.getMediaId()));
+ }
+
+ @Override
+ public void onAddQueueItem(MediaDescriptionCompat description, int index) {
+ if (listener == null) return;
+ listener.onAddQueueItemAt(getMediaMetadata(description.getMediaId()), index);
+ }
+
+ @Override
+ public void onRemoveQueueItem(MediaDescriptionCompat description) {
+ if (listener == null) return;
+ listener.onRemoveQueueItem(getMediaMetadata(description.getMediaId()));
+ }
+
+ @Override
+ public void onPrepare() {
+ if (listener == null) return;
+ if (!mediaSession.isActive())
+ mediaSession.setActive(true);
+ listener.onPrepare();
+ }
+
+ @Override
+ public void onPrepareFromMediaId(String mediaId, Bundle extras) {
+ if (listener == null) return;
+ if (!mediaSession.isActive())
+ mediaSession.setActive(true);
+ listener.onPrepareFromMediaId(mediaId, extras);
+ }
+
+ @Override
+ public void onPrepareFromSearch(String query, Bundle extras) {
+ if (listener == null) return;
+ if (!mediaSession.isActive())
+ mediaSession.setActive(true);
+ listener.onPrepareFromSearch(query, extras);
+ }
+
+ @Override
+ public void onPrepareFromUri(Uri uri, Bundle extras) {
+ if (listener == null) return;
+ if (!mediaSession.isActive())
+ mediaSession.setActive(true);
+ listener.onPrepareFromUri(uri, extras);
+ }
+
+ @Override
+ public void onPlay() {
+ if (listener == null) return;
+ listener.onPlay();
+ }
+
+ @Override
+ public void onPlayFromMediaId(final String mediaId, final Bundle extras) {
+ if (listener == null) return;
+ listener.onPlayFromMediaId(mediaId, extras);
+ }
+
+ @Override
+ public void onPlayFromSearch(final String query, final Bundle extras) {
+ if (listener == null) return;
+ listener.onPlayFromSearch(query, extras);
+ }
+
+ @Override
+ public void onPlayFromUri(final Uri uri, final Bundle extras) {
+ if (listener == null) return;
+ listener.onPlayFromUri(uri, extras);
+ }
+
+ @Override
+ public boolean onMediaButtonEvent(Intent mediaButtonEvent) {
+ if (listener == null) return false;
+ // TODO: use typesafe version once SDK 33 is released.
+ @SuppressWarnings("deprecation")
+ final KeyEvent event = (KeyEvent)mediaButtonEvent.getExtras().getParcelable(Intent.EXTRA_KEY_EVENT);
+ if (event.getAction() == KeyEvent.ACTION_DOWN) {
+ switch (event.getKeyCode()) {
+ case KEYCODE_BYPASS_PLAY:
+ onPlay();
+ break;
+ case KEYCODE_BYPASS_PAUSE:
+ onPause();
+ break;
+ case KeyEvent.KEYCODE_MEDIA_STOP:
+ onStop();
+ break;
+ case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
+ onFastForward();
+ break;
+ case KeyEvent.KEYCODE_MEDIA_REWIND:
+ onRewind();
+ break;
+ // Android unfortunately reroutes media button clicks to
+ // KEYCODE_MEDIA_PLAY/PAUSE instead of the expected KEYCODE_HEADSETHOOK
+ // or KEYCODE_MEDIA_PLAY_PAUSE. As a result, we can't genuinely tell if
+ // onMediaButtonEvent was called because a media button was actually
+ // pressed or because a PLAY/PAUSE action was pressed instead! To get
+ // around this, we make PLAY and PAUSE actions use different keycodes:
+ // KEYCODE_BYPASS_PLAY/PAUSE. Now if we get KEYCODE_MEDIA_PLAY/PUASE
+ // we know it is actually a media button press.
+ case KeyEvent.KEYCODE_MEDIA_NEXT:
+ case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
+ case KeyEvent.KEYCODE_MEDIA_PLAY:
+ case KeyEvent.KEYCODE_MEDIA_PAUSE:
+ // These are the "genuine" media button click events
+ case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
+ case KeyEvent.KEYCODE_HEADSETHOOK:
+ listener.onClick(eventToButton(event));
+ break;
+ }
+ }
+ return true;
+ }
+
+ private MediaButton eventToButton(KeyEvent event) {
+ switch (event.getKeyCode()) {
+ case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
+ case KeyEvent.KEYCODE_HEADSETHOOK:
+ return MediaButton.media;
+ case KeyEvent.KEYCODE_MEDIA_NEXT:
+ return MediaButton.next;
+ case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
+ return MediaButton.previous;
+ default:
+ return MediaButton.media;
+ }
+ }
+
+ @Override
+ public void onPause() {
+ if (listener == null) return;
+ listener.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ if (listener == null) return;
+ listener.onStop();
+ }
+
+ @Override
+ public void onSkipToNext() {
+ if (listener == null) return;
+ listener.onSkipToNext();
+ }
+
+ @Override
+ public void onSkipToPrevious() {
+ if (listener == null) return;
+ listener.onSkipToPrevious();
+ }
+
+ @Override
+ public void onFastForward() {
+ if (listener == null) return;
+ listener.onFastForward();
+ }
+
+ @Override
+ public void onRewind() {
+ if (listener == null) return;
+ listener.onRewind();
+ }
+
+ @Override
+ public void onSkipToQueueItem(long id) {
+ if (listener == null) return;
+ listener.onSkipToQueueItem(id);
+ }
+
+ @Override
+ public void onSeekTo(long pos) {
+ if (listener == null) return;
+ listener.onSeekTo(pos);
+ }
+
+ @Override
+ public void onSetRating(RatingCompat rating) {
+ if (listener == null) return;
+ listener.onSetRating(rating);
+ }
+
+ @Override
+ public void onSetPlaybackSpeed(float speed) {
+ if (listener == null) return;
+ listener.onSetPlaybackSpeed(speed);
+ }
+
+ @Override
+ public void onSetCaptioningEnabled(boolean enabled) {
+ if (listener == null) return;
+ listener.onSetCaptioningEnabled(enabled);
+ }
+
+ @Override
+ public void onSetRepeatMode(int repeatMode) {
+ if (listener == null) return;
+ listener.onSetRepeatMode(repeatMode);
+ }
+
+ @Override
+ public void onSetShuffleMode(int shuffleMode) {
+ if (listener == null) return;
+ listener.onSetShuffleMode(shuffleMode);
+ }
+
+ @Override
+ public void onCustomAction(String action, Bundle extras) {
+ if (listener == null) return;
+ if (CUSTOM_ACTION_STOP.equals(action)) {
+ listener.onStop();
+ } else if (CUSTOM_ACTION_FAST_FORWARD.equals(action)) {
+ listener.onFastForward();
+ } else if (CUSTOM_ACTION_REWIND.equals(action)) {
+ listener.onRewind();
+ } else {
+ listener.onCustomAction(action, extras);
+ }
+ }
+
+ @Override
+ public void onSetRating(RatingCompat rating, Bundle extras) {
+ if (listener == null) return;
+ listener.onSetRating(rating, extras);
+ }
+
+ //
+ // NON-STANDARD METHODS
+ //
+
+ public void onPlayMediaItem(final MediaDescriptionCompat description) {
+ if (listener == null) return;
+ listener.onPlayMediaItem(getMediaMetadata(description.getMediaId()));
+ }
+ }
+
+ public interface ServiceListener {
+ //BrowserRoot onGetRoot(String clientPackageName, int clientUid, Bundle rootHints);
+ void onLoadChildren(String parentMediaId, Result<List<MediaBrowserCompat.MediaItem>> result, Bundle options);
+ void onLoadItem(String itemId, Result<MediaBrowserCompat.MediaItem> result);
+ void onSearch(String query, Bundle extras, Result<List<MediaBrowserCompat.MediaItem>> result);
+ void onClick(MediaButton mediaButton);
+ void onPrepare();
+ void onPrepareFromMediaId(String mediaId, Bundle extras);
+ void onPrepareFromSearch(String query, Bundle extras);
+ void onPrepareFromUri(Uri uri, Bundle extras);
+ void onPlay();
+ void onPlayFromMediaId(String mediaId, Bundle extras);
+ void onPlayFromSearch(String query, Bundle extras);
+ void onPlayFromUri(Uri uri, Bundle extras);
+ void onSkipToQueueItem(long id);
+ void onPause();
+ void onSkipToNext();
+ void onSkipToPrevious();
+ void onFastForward();
+ void onRewind();
+ void onStop();
+ void onSeekTo(long pos);
+ void onSetRating(RatingCompat rating);
+ void onSetRating(RatingCompat rating, Bundle extras);
+ void onSetRepeatMode(int repeatMode);
+ void onSetShuffleMode(int shuffleMode);
+ void onCustomAction(String action, Bundle extras);
+ void onAddQueueItem(MediaMetadataCompat metadata);
+ void onAddQueueItemAt(MediaMetadataCompat metadata, int index);
+ void onRemoveQueueItem(MediaMetadataCompat metadata);
+ void onRemoveQueueItemAt(int index);
+ void onSetPlaybackSpeed(float speed);
+ void onSetCaptioningEnabled(boolean enabled);
+ void onSetVolumeTo(int volumeIndex);
+ void onAdjustVolume(int direction);
+
+ //
+ // NON-STANDARD METHODS
+ //
+
+ void onPlayMediaItem(MediaMetadataCompat metadata);
+ void onTaskRemoved();
+ void onClose();
+ void onDestroy();
+ }
+}
diff --git a/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioServiceActivity.java b/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioServiceActivity.java
new file mode 100644
index 00000000..f91f663b
--- /dev/null
+++ b/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioServiceActivity.java
@@ -0,0 +1,15 @@
+package com.ryanheise.audioservice;
+
+import android.content.Context;
+
+import androidx.annotation.NonNull;
+
+import io.flutter.embedding.android.FlutterActivity;
+import io.flutter.embedding.engine.FlutterEngine;
+
+public class AudioServiceActivity extends FlutterActivity {
+ @Override
+ public FlutterEngine provideFlutterEngine(@NonNull Context context) {
+ return AudioServicePlugin.getFlutterEngine(context);
+ }
+}
diff --git a/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioServiceConfig.java b/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioServiceConfig.java
new file mode 100644
index 00000000..1917989d
--- /dev/null
+++ b/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioServiceConfig.java
@@ -0,0 +1,120 @@
+package com.ryanheise.audioservice;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.os.Bundle;
+import java.util.Iterator;
+import java.util.Map;
+import org.json.JSONObject;
+
+public class AudioServiceConfig {
+ private static final String SHARED_PREFERENCES_NAME = "audio_service_preferences";
+ private static final String KEY_ANDROID_RESUME_ON_CLICK = "androidResumeOnClick";
+ private static final String KEY_ANDROID_NOTIFICATION_CHANNEL_ID = "androidNotificationChannelId";
+ private static final String KEY_ANDROID_NOTIFICATION_CHANNEL_NAME = "androidNotificationChannelName";
+ private static final String KEY_ANDROID_NOTIFICATION_CHANNEL_DESCRIPTION = "androidNotificationChannelDescription";
+ private static final String KEY_NOTIFICATION_COLOR = "notificationColor";
+ private static final String KEY_ANDROID_NOTIFICATION_ICON = "androidNotificationIcon";
+ private static final String KEY_ANDROID_SHOW_NOTIFICATION_BADGE = "androidShowNotificationBadge";
+ private static final String KEY_ANDROID_NOTIFICATION_CLICK_STARTS_ACTIVITY = "androidNotificationClickStartsActivity";
+ private static final String KEY_ANDROID_NOTIFICATION_ONGOING = "androidNotificationOngoing";
+ private static final String KEY_ANDROID_STOP_FOREGROUND_ON_PAUSE = "androidStopForegroundOnPause";
+ private static final String KEY_ART_DOWNSCALE_WIDTH = "artDownscaleWidth";
+ private static final String KEY_ART_DOWNSCALE_HEIGHT = "artDownscaleHeight";
+ private static final String KEY_ACTIVITY_CLASS_NAME = "activityClassName";
+ private static final String KEY_BROWSABLE_ROOT_EXTRAS = "androidBrowsableRootExtras";
+
+ private SharedPreferences preferences;
+ public boolean androidResumeOnClick;
+ public String androidNotificationChannelId;
+ public String androidNotificationChannelName;
+ public String androidNotificationChannelDescription;
+ public int notificationColor;
+ public String androidNotificationIcon;
+ public boolean androidShowNotificationBadge;
+ public boolean androidNotificationClickStartsActivity;
+ public boolean androidNotificationOngoing;
+ public boolean androidStopForegroundOnPause;
+ public int artDownscaleWidth;
+ public int artDownscaleHeight;
+ public String activityClassName;
+ public String browsableRootExtras;
+
+ public AudioServiceConfig(Context context) {
+ preferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
+ androidResumeOnClick = preferences.getBoolean(KEY_ANDROID_RESUME_ON_CLICK, true);
+ androidNotificationChannelId = preferences.getString(KEY_ANDROID_NOTIFICATION_CHANNEL_ID, null);
+ androidNotificationChannelName = preferences.getString(KEY_ANDROID_NOTIFICATION_CHANNEL_NAME, null);
+ androidNotificationChannelDescription = preferences.getString(KEY_ANDROID_NOTIFICATION_CHANNEL_DESCRIPTION, null);
+ notificationColor = preferences.getInt(KEY_NOTIFICATION_COLOR, -1);
+ androidNotificationIcon = preferences.getString(KEY_ANDROID_NOTIFICATION_ICON, "mipmap/ic_launcher");
+ androidShowNotificationBadge = preferences.getBoolean(KEY_ANDROID_SHOW_NOTIFICATION_BADGE, false);
+ androidNotificationClickStartsActivity = preferences.getBoolean(KEY_ANDROID_NOTIFICATION_CLICK_STARTS_ACTIVITY, true);
+ androidNotificationOngoing = preferences.getBoolean(KEY_ANDROID_NOTIFICATION_ONGOING, false);
+ androidStopForegroundOnPause = preferences.getBoolean(KEY_ANDROID_STOP_FOREGROUND_ON_PAUSE, true);
+ artDownscaleWidth = preferences.getInt(KEY_ART_DOWNSCALE_WIDTH, -1);
+ artDownscaleHeight = preferences.getInt(KEY_ART_DOWNSCALE_HEIGHT, -1);
+ activityClassName = preferences.getString(KEY_ACTIVITY_CLASS_NAME, null);
+ browsableRootExtras = preferences.getString(KEY_BROWSABLE_ROOT_EXTRAS, null);
+ }
+
+ public void setBrowsableRootExtras(Map<?,?> map) {
+ if (map != null) {
+ JSONObject json = new JSONObject(map);
+ browsableRootExtras = json.toString();
+ } else {
+ browsableRootExtras = null;
+ }
+ }
+
+ public Bundle getBrowsableRootExtras() {
+ if (browsableRootExtras == null) return null;
+ try {
+ JSONObject json = new JSONObject(browsableRootExtras);
+ Bundle extras = new Bundle();
+ for (Iterator<String> it = json.keys(); it.hasNext();) {
+ String key = it.next();
+ try {
+ extras.putInt(key, json.getInt(key));
+ } catch (Exception e1) {
+ try {
+ extras.putBoolean(key, json.getBoolean(key));
+ } catch (Exception e2) {
+ try {
+ extras.putDouble(key, json.getDouble(key));
+ } catch (Exception e3) {
+ try {
+ extras.putString(key, json.getString(key));
+ } catch (Exception e4) {
+ System.out.println("Unsupported extras value for key " + key);
+ }
+ }
+ }
+ }
+ }
+ return extras;
+ } catch (Exception e) {
+ e.printStackTrace();
+ return null;
+ }
+ }
+
+ public void save() {
+ preferences.edit()
+ .putBoolean(KEY_ANDROID_RESUME_ON_CLICK, androidResumeOnClick)
+ .putString(KEY_ANDROID_NOTIFICATION_CHANNEL_ID, androidNotificationChannelId)
+ .putString(KEY_ANDROID_NOTIFICATION_CHANNEL_NAME, androidNotificationChannelName)
+ .putString(KEY_ANDROID_NOTIFICATION_CHANNEL_DESCRIPTION, androidNotificationChannelDescription)
+ .putInt(KEY_NOTIFICATION_COLOR, notificationColor)
+ .putString(KEY_ANDROID_NOTIFICATION_ICON, androidNotificationIcon)
+ .putBoolean(KEY_ANDROID_SHOW_NOTIFICATION_BADGE, androidShowNotificationBadge)
+ .putBoolean(KEY_ANDROID_NOTIFICATION_CLICK_STARTS_ACTIVITY, androidNotificationClickStartsActivity)
+ .putBoolean(KEY_ANDROID_NOTIFICATION_ONGOING, androidNotificationOngoing)
+ .putBoolean(KEY_ANDROID_STOP_FOREGROUND_ON_PAUSE, androidStopForegroundOnPause)
+ .putInt(KEY_ART_DOWNSCALE_WIDTH, artDownscaleWidth)
+ .putInt(KEY_ART_DOWNSCALE_HEIGHT, artDownscaleHeight)
+ .putString(KEY_ACTIVITY_CLASS_NAME, activityClassName)
+ .putString(KEY_BROWSABLE_ROOT_EXTRAS, browsableRootExtras)
+ .apply();
+ }
+}
diff --git a/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioServiceFragmentActivity.java b/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioServiceFragmentActivity.java
new file mode 100644
index 00000000..723fbbaa
--- /dev/null
+++ b/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioServiceFragmentActivity.java
@@ -0,0 +1,48 @@
+package com.ryanheise.audioservice;
+
+import android.content.Context;
+
+import android.os.Bundle;
+import androidx.annotation.NonNull;
+
+import androidx.annotation.Nullable;
+import io.flutter.embedding.android.FlutterFragmentActivity;
+import io.flutter.embedding.engine.FlutterEngine;
+
+public class AudioServiceFragmentActivity extends FlutterFragmentActivity {
+ @Override
+ public FlutterEngine provideFlutterEngine(@NonNull Context context) {
+ return AudioServicePlugin.getFlutterEngine(context);
+ }
+
+ @Override
+ protected void onCreate(@Nullable Bundle savedInstanceState) {
+ AudioServicePlugin.getFlutterEngine(this);
+ super.onCreate(savedInstanceState);
+ }
+
+ @Override
+ protected String getCachedEngineId() {
+ AudioServicePlugin.getFlutterEngine(this);
+ return AudioServicePlugin.getFlutterEngineId();
+ }
+
+ // The engine is created and managed by AudioServicePlugin,
+ // it should not be destroyed with the activity.
+ @Override
+ public boolean shouldDestroyEngineWithHost() {
+ return false;
+ }
+
+ // Make this protected method public
+ @Override
+ public String getInitialRoute() {
+ return super.getInitialRoute();
+ }
+
+ // Make this protected method public
+ @Override
+ public boolean shouldHandleDeeplinking() {
+ return super.shouldHandleDeeplinking();
+ }
+}
diff --git a/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioServicePlugin.java b/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioServicePlugin.java
new file mode 100644
index 00000000..b776a840
--- /dev/null
+++ b/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioServicePlugin.java
@@ -0,0 +1,1254 @@
+package com.ryanheise.audioservice;
+
+import android.app.Activity;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.media.AudioFormat;
+import android.media.AudioManager;
+import android.media.AudioTrack;
+import android.os.Build;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.SystemClock;
+
+import androidx.annotation.UiThread;
+import androidx.core.app.NotificationCompat;
+
+import android.support.v4.media.MediaBrowserCompat;
+
+import androidx.media.MediaBrowserServiceCompat;
+
+import android.support.v4.media.MediaDescriptionCompat;
+import android.support.v4.media.MediaMetadataCompat;
+import android.support.v4.media.RatingCompat;
+import android.support.v4.media.session.MediaControllerCompat;
+import android.support.v4.media.session.MediaSessionCompat;
+import android.support.v4.media.session.PlaybackStateCompat;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.Executors;
+
+import io.flutter.embedding.android.FlutterActivity;
+import io.flutter.embedding.android.FlutterFragmentActivity;
+import io.flutter.embedding.engine.plugins.FlutterPlugin;
+import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
+import io.flutter.embedding.engine.plugins.activity.ActivityAware;
+import io.flutter.plugin.common.MethodCall;
+import io.flutter.plugin.common.MethodChannel;
+import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
+import io.flutter.plugin.common.MethodChannel.Result;
+import io.flutter.plugin.common.PluginRegistry.NewIntentListener;
+import io.flutter.plugin.common.BinaryMessenger;
+
+import io.flutter.embedding.engine.FlutterEngine;
+import io.flutter.embedding.engine.FlutterEngineCache;
+import io.flutter.embedding.engine.dart.DartExecutor;
+
+import android.net.Uri;
+import android.util.Log;
+
+/**
+ * AudioservicePlugin
+ */
+public class AudioServicePlugin implements FlutterPlugin, ActivityAware {
+ private static String flutterEngineId = "audio_service_engine";
+ /** Must be called BEFORE any FlutterEngine is created. e.g. in Application class. */
+ public static void setFlutterEngineId(String id) {
+ flutterEngineId = id;
+ }
+ public static String getFlutterEngineId() {
+ return flutterEngineId;
+ }
+ public static synchronized FlutterEngine getFlutterEngine(Context context) {
+ FlutterEngine flutterEngine = FlutterEngineCache.getInstance().get(flutterEngineId);
+ if (flutterEngine == null) {
+ // XXX: The constructor triggers onAttachedToEngine so this variable doesn't help us.
+ // Maybe need a boolean flag to tell us we're currently loading the main flutter engine.
+ flutterEngine = new FlutterEngine(context.getApplicationContext());
+ String initialRoute = null;
+ if (context instanceof FlutterActivity) {
+ final FlutterActivity activity = (FlutterActivity)context;
+ initialRoute = activity.getInitialRoute();
+ if (initialRoute == null) {
+ if (activity.shouldHandleDeeplinking()) {
+ Uri data = activity.getIntent().getData();
+ if (data != null) {
+ initialRoute = data.getPath();
+ if (data.getQuery() != null && !data.getQuery().isEmpty()) {
+ initialRoute += "?" + data.getQuery();
+ }
+ }
+ }
+ }
+ } else if (context instanceof AudioServiceFragmentActivity) {
+ final AudioServiceFragmentActivity activity = (AudioServiceFragmentActivity)context;
+ initialRoute = activity.getInitialRoute();
+ if (initialRoute == null) {
+ if (activity.shouldHandleDeeplinking()) {
+ Uri data = activity.getIntent().getData();
+ if (data != null) {
+ initialRoute = data.getPath();
+ if (data.getQuery() != null && !data.getQuery().isEmpty()) {
+ initialRoute += "?" + data.getQuery();
+ }
+ }
+ }
+ }
+ }
+ if (initialRoute == null) {
+ initialRoute = "/";
+ }
+ flutterEngine.getNavigationChannel().setInitialRoute(initialRoute);
+ flutterEngine.getDartExecutor().executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault());
+ FlutterEngineCache.getInstance().put(flutterEngineId, flutterEngine);
+ }
+ return flutterEngine;
+ }
+
+ public static synchronized void disposeFlutterEngine() {
+ for (ClientInterface clientInterface : clientInterfaces) {
+ if (clientInterface.activity != null) {
+ // Don't destroy the engine if a new activity started and
+ // bound to the service in the time since the previous activity
+ // unbound from it.
+ return;
+ }
+ }
+ FlutterEngine flutterEngine = FlutterEngineCache.getInstance().get(flutterEngineId);
+ if (flutterEngine != null) {
+ flutterEngine.destroy();
+ FlutterEngineCache.getInstance().remove(flutterEngineId);
+ }
+ }
+
+ private static final String CHANNEL_CLIENT = "com.ryanheise.audio_service.client.methods";
+ private static final String CHANNEL_HANDLER = "com.ryanheise.audio_service.handler.methods";
+
+ private static final Set<ClientInterface> clientInterfaces = new HashSet<>();
+ private static ClientInterface mainClientInterface;
+ private static AudioHandlerInterface audioHandlerInterface;
+ private static final long bootTime;
+ private static Result configureResult;
+ private static boolean flutterReady;
+
+ static {
+ bootTime = System.currentTimeMillis() - SystemClock.elapsedRealtime();
+ }
+
+ static AudioHandlerInterface audioHandlerInterface() throws Exception {
+ if (audioHandlerInterface == null) throw new Exception("Background audio task not running");
+ return audioHandlerInterface;
+ }
+
+ private static MediaBrowserCompat mediaBrowser;
+ private static MediaControllerCompat mediaController;
+ private static final MediaControllerCompat.Callback controllerCallback = new MediaControllerCompat.Callback() {
+// @Override
+// public void onMetadataChanged(MediaMetadataCompat metadata) {
+// Map<String, Object> map = new HashMap<>();
+// map.put("mediaItem", mediaMetadata2raw(metadata));
+// invokeClientMethod("onMediaItemChanged", map);
+// }
+//
+// @Override
+// public void onPlaybackStateChanged(PlaybackStateCompat state) {
+// // On the native side, we represent the update time relative to the boot time.
+// // On the flutter side, we represent the update time relative to the epoch.
+// long updateTimeSinceBoot = state.getLastPositionUpdateTime();
+// long updateTimeSinceEpoch = bootTime + updateTimeSinceBoot;
+// Map<String, Object> stateMap = new HashMap<>();
+// stateMap.put("processingState", AudioService.instance.getProcessingState().ordinal());
+// stateMap.put("playing", AudioService.instance.isPlaying());
+// stateMap.put("controls", new ArrayList<>());
+// long actionBits = state.getActions();
+// List<Object> systemActions = new ArrayList<>();
+// for (int actionIndex = 0; actionIndex < 64; actionIndex++) {
+// if ((actionBits & (1 << actionIndex)) != 0) {
+// systemActions.add(actionIndex);
+// }
+// }
+// stateMap.put("systemActions", systemActions);
+// stateMap.put("updatePosition", state.getPosition());
+// stateMap.put("bufferedPosition", state.getBufferedPosition());
+// stateMap.put("speed", state.getPlaybackSpeed());
+// stateMap.put("updateTime", updateTimeSinceEpoch);
+// stateMap.put("repeatMode", AudioService.instance.getRepeatMode());
+// stateMap.put("shuffleMode", AudioService.instance.getShuffleMode());
+// Map<String, Object> map = new HashMap<>();
+// map.put("state", stateMap);
+// invokeClientMethod("onPlaybackStateChanged", map);
+// }
+//
+// @Override
+// public void onQueueChanged(List<MediaSessionCompat.QueueItem> queue) {
+// Map<String, Object> map = new HashMap<>();
+// map.put("queue", queue2raw(queue));
+// invokeClientMethod("onQueueChanged", map);
+// }
+ };
+// private static void invokeClientMethod(String method, Object arg) {
+// for (ClientInterface clientInterface : clientInterfaces) {
+// clientInterface.channel.invokeMethod(method, arg);
+// }
+// }
+
+ //
+ // INSTANCE FIELDS AND METHODS
+ //
+
+ private Context applicationContext;
+ private FlutterPluginBinding flutterPluginBinding;
+ private ActivityPluginBinding activityPluginBinding;
+ private NewIntentListener newIntentListener;
+ private ClientInterface clientInterface;
+ private final MediaBrowserCompat.ConnectionCallback connectionCallback = new MediaBrowserCompat.ConnectionCallback() {
+ @Override
+ public void onConnected() {
+ if (applicationContext == null) return;
+ try {
+ MediaSessionCompat.Token token = mediaBrowser.getSessionToken();
+ mediaController = new MediaControllerCompat(applicationContext, token);
+ Activity activity = mainClientInterface != null ? mainClientInterface.activity : null;
+ if (activity != null) {
+ MediaControllerCompat.setMediaController(activity, mediaController);
+ }
+ mediaController.registerCallback(controllerCallback);
+ // PlaybackStateCompat state = mediaController.getPlaybackState();
+ // controllerCallback.onPlaybackStateChanged(state);
+ // MediaMetadataCompat metadata = mediaController.getMetadata();
+ // controllerCallback.onQueueChanged(mediaController.getQueue());
+ // controllerCallback.onMetadataChanged(metadata);
+ if (configureResult != null) {
+ configureResult.success(mapOf());
+ configureResult = null;
+ }
+ } catch (Exception e) {
+ System.out.println("onConnected error: " + e.getMessage());
+ e.printStackTrace();
+ if (configureResult != null) {
+ configureResult.error("onConnected error: " + e.getMessage(), null, null);
+ } else {
+ clientInterface.setServiceConnectionFailed(true);
+ }
+ }
+ }
+
+ @Override
+ public void onConnectionSuspended() {
+ // TODO: Handle this
+ System.out.println("### UNHANDLED: onConnectionSuspended");
+ }
+
+ @Override
+ public void onConnectionFailed() {
+ if (configureResult != null) {
+ configureResult.error("Unable to bind to AudioService. Please ensure you have declared a <service> element as described in the README.", null, null);
+ } else {
+ clientInterface.setServiceConnectionFailed(true);
+ }
+ }
+ };
+
+
+ //
+ // FlutterPlugin callbacks
+ //
+
+ @Override
+ public void onAttachedToEngine(FlutterPluginBinding binding) {
+ flutterPluginBinding = binding;
+ clientInterface = new ClientInterface(flutterPluginBinding.getBinaryMessenger());
+ clientInterface.setContext(flutterPluginBinding.getApplicationContext());
+ clientInterfaces.add(clientInterface);
+ if (applicationContext == null) {
+ applicationContext = flutterPluginBinding.getApplicationContext();
+ }
+ if (audioHandlerInterface == null) {
+ // We don't know yet whether this is the right engine that hosts the AudioHandler,
+ // but we need to register a MethodCallHandler now just in case. If we're wrong, we
+ // detect and correct this when receiving the "configure" message.
+ audioHandlerInterface = new AudioHandlerInterface(flutterPluginBinding.getBinaryMessenger());
+ AudioService.init(audioHandlerInterface);
+ }
+ if (mediaBrowser == null) {
+ connect();
+ }
+ }
+
+ @Override
+ public void onDetachedFromEngine(FlutterPluginBinding binding) {
+ if (clientInterfaces.size() == 1) {
+ disconnect();
+ }
+ clientInterfaces.remove(clientInterface);
+ clientInterface.setContext(null);
+ clientInterface = null;
+ applicationContext = null;
+ if (audioHandlerInterface != null
+ && audioHandlerInterface.messenger == flutterPluginBinding.getBinaryMessenger()) {
+ System.out.println("### destroying audio handler interface");
+ audioHandlerInterface.destroy();
+ audioHandlerInterface = null;
+ }
+ flutterPluginBinding = null;
+ }
+
+ //
+ // ActivityAware callbacks
+ //
+
+ @Override
+ public void onAttachedToActivity(ActivityPluginBinding binding) {
+ activityPluginBinding = binding;
+ clientInterface.setActivity(binding.getActivity());
+ clientInterface.setContext(binding.getActivity());
+ // Verify that the app is configured with the correct FlutterEngine.
+ FlutterEngine sharedEngine = getFlutterEngine(binding.getActivity());
+ clientInterface.setWrongEngineDetected(flutterPluginBinding.getBinaryMessenger() != sharedEngine.getDartExecutor());
+ mainClientInterface = clientInterface;
+ registerOnNewIntentListener();
+ if (mediaController != null) {
+ MediaControllerCompat.setMediaController(mainClientInterface.activity, mediaController);
+ }
+ if (mediaBrowser == null) {
+ connect();
+ }
+
+ Activity activity = mainClientInterface.activity;
+ if (clientInterface.wasLaunchedFromRecents()) {
+ // We do this to avoid using the old intent.
+ activity.setIntent(new Intent(Intent.ACTION_MAIN));
+ }
+ sendNotificationClicked();
+ }
+
+ @Override
+ public void onDetachedFromActivityForConfigChanges() {
+ activityPluginBinding.removeOnNewIntentListener(newIntentListener);
+ activityPluginBinding = null;
+ clientInterface.setActivity(null);
+ clientInterface.setContext(flutterPluginBinding.getApplicationContext());
+ }
+
+ @Override
+ public void onReattachedToActivityForConfigChanges(ActivityPluginBinding binding) {
+ activityPluginBinding = binding;
+ clientInterface.setActivity(binding.getActivity());
+ clientInterface.setContext(binding.getActivity());
+ registerOnNewIntentListener();
+ }
+
+ @Override
+ public void onDetachedFromActivity() {
+ activityPluginBinding.removeOnNewIntentListener(newIntentListener);
+ activityPluginBinding = null;
+ newIntentListener = null;
+ clientInterface.setActivity(null);
+ clientInterface.setContext(flutterPluginBinding.getApplicationContext());
+ if (clientInterfaces.size() == 1) {
+ // This unbinds from the service allowing AudioService.onDestroy to
+ // happen which in turn allows the FlutterEngine to be destroyed.
+ disconnect();
+ }
+ if (clientInterface == mainClientInterface) {
+ mainClientInterface = null;
+ }
+ }
+
+ private void connect() {
+ if (mediaBrowser == null) {
+ mediaBrowser = new MediaBrowserCompat(applicationContext,
+ new ComponentName(applicationContext, AudioService.class),
+ connectionCallback,
+ null);
+ mediaBrowser.connect();
+ }
+ }
+
+ private void disconnect() {
+ Activity activity = mainClientInterface != null ? mainClientInterface.activity : null;
+ if (activity != null) {
+ // Since the activity enters paused state, we set the intent with ACTION_MAIN.
+ activity.setIntent(new Intent(Intent.ACTION_MAIN));
+ }
+
+ if (mediaController != null) {
+ mediaController.unregisterCallback(controllerCallback);
+ mediaController = null;
+ }
+ if (mediaBrowser != null) {
+ mediaBrowser.disconnect();
+ mediaBrowser = null;
+ }
+ }
+
+ private void registerOnNewIntentListener() {
+ activityPluginBinding.addOnNewIntentListener(newIntentListener = (intent) -> {
+ clientInterface.activity.setIntent(intent);
+ sendNotificationClicked();
+ return true;
+ });
+ }
+
+ private void sendNotificationClicked() {
+ Activity activity = clientInterface.activity;
+ if (audioHandlerInterface != null && activity.getIntent().getAction() != null) {
+ boolean clicked = activity.getIntent().getAction().equals(AudioService.NOTIFICATION_CLICK_ACTION);
+ audioHandlerInterface.invokeMethod("onNotificationClicked", mapOf("clicked", clicked));
+ }
+ }
+
+ private static class ClientInterface implements MethodCallHandler {
+ private Context context;
+ private Activity activity;
+ public final BinaryMessenger messenger;
+ private final MethodChannel channel;
+ private boolean wrongEngineDetected;
+ private boolean serviceConnectionFailed;
+
+ // This is implemented in Dart already.
+ // But we may need to bring this back if we want to connect to another process's media session.
+// private final MediaBrowserCompat.SubscriptionCallback subscriptionCallback = new MediaBrowserCompat.SubscriptionCallback() {
+// @Override
+// public void onChildrenLoaded(@NonNull String parentId, @NonNull List<MediaBrowserCompat.MediaItem> children) {
+// Map<String, Object> map = new HashMap<String, Object>();
+// map.put("parentMediaId", parentId);
+// map.put("children", mediaItems2raw(children));
+// invokeClientMethod("onChildrenLoaded", map);
+// }
+// };
+
+ public ClientInterface(BinaryMessenger messenger) {
+ this.messenger = messenger;
+ channel = new MethodChannel(messenger, CHANNEL_CLIENT);
+ channel.setMethodCallHandler(this);
+ }
+
+ private void setContext(Context context) {
+ this.context = context;
+ }
+
+ private void setActivity(Activity activity) {
+ this.activity = activity;
+ }
+
+ public void setWrongEngineDetected(boolean value) {
+ wrongEngineDetected = value;
+ }
+
+ public void setServiceConnectionFailed(boolean value) {
+ serviceConnectionFailed = value;
+ }
+
+ // See: https://stackoverflow.com/questions/13135545/android-activity-is-using-old-intent-if-launching-app-from-recent-task
+ protected boolean wasLaunchedFromRecents() {
+ return (activity.getIntent().getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY;
+ }
+
+ @Override
+ public void onMethodCall(MethodCall call, final Result result) {
+ try {
+ if (wrongEngineDetected) {
+ throw new IllegalStateException("The Activity class declared in your AndroidManifest.xml is wrong or has not provided the correct FlutterEngine. Please see the README for instructions.");
+ }
+ switch (call.method) {
+ case "configure":
+ if (serviceConnectionFailed) {
+ throw new IllegalStateException("Unable to bind to AudioService. Please ensure you have declared a <service> element as described in the README.");
+ }
+ flutterReady = true;
+ Map<?, ?> args = (Map<?, ?>)call.arguments;
+ Map<?, ?> configMap = (Map<?, ?>)args.get("config");
+ AudioServiceConfig config = new AudioServiceConfig(context.getApplicationContext());
+ config.androidNotificationClickStartsActivity = (Boolean)configMap.get("androidNotificationClickStartsActivity");
+ config.androidNotificationOngoing = (Boolean)configMap.get("androidNotificationOngoing");
+ config.androidResumeOnClick = (Boolean)configMap.get("androidResumeOnClick");
+ config.androidNotificationChannelId = (String)configMap.get("androidNotificationChannelId");
+ config.androidNotificationChannelName = (String)configMap.get("androidNotificationChannelName");
+ config.androidNotificationChannelDescription = (String)configMap.get("androidNotificationChannelDescription");
+ config.notificationColor = configMap.get("notificationColor") == null ? -1 : getInt(configMap.get("notificationColor"));
+ config.androidNotificationIcon = (String)configMap.get("androidNotificationIcon");
+ config.androidShowNotificationBadge = (Boolean)configMap.get("androidShowNotificationBadge");
+ config.androidStopForegroundOnPause = (Boolean)configMap.get("androidStopForegroundOnPause");
+ config.artDownscaleWidth = configMap.get("artDownscaleWidth") != null ? (Integer)configMap.get("artDownscaleWidth") : -1;
+ config.artDownscaleHeight = configMap.get("artDownscaleHeight") != null ? (Integer)configMap.get("artDownscaleHeight") : -1;
+ config.setBrowsableRootExtras((Map<?,?>)configMap.get("androidBrowsableRootExtras"));
+ if (activity != null) {
+ config.activityClassName = activity.getClass().getName();
+ }
+ config.save();
+ if (AudioService.instance != null) {
+ AudioService.instance.configure(config);
+ }
+ mainClientInterface = ClientInterface.this;
+ if (audioHandlerInterface == null) {
+ audioHandlerInterface = new AudioHandlerInterface(messenger);
+ AudioService.init(audioHandlerInterface);
+ } else {
+ if (audioHandlerInterface.messenger != messenger) {
+ // We've detected this is the real engine hosting the AudioHandler,
+ // so update AudioHandlerInterface to connect to it.
+ audioHandlerInterface.switchToMessenger(messenger);
+ }
+ audioHandlerInterface.invokePendingMethods();
+ }
+ if (mediaController != null) {
+ result.success(mapOf());
+ } else {
+ configureResult = result;
+ }
+ break;
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ result.error(e.getMessage(), null, null);
+ }
+ }
+ }
+
+ private static class AudioHandlerInterface implements MethodCallHandler, AudioService.ServiceListener {
+ private static final int SILENCE_SAMPLE_RATE = 44100;
+ public BinaryMessenger messenger;
+ public MethodChannel channel;
+ private AudioTrack silenceAudioTrack;
+ private final Handler handler = new Handler(Looper.getMainLooper());
+ private List<MethodInvocation> methodInvocationQueue = new LinkedList<MethodInvocation>();
+
+ public AudioHandlerInterface(BinaryMessenger messenger) {
+ this.messenger = messenger;
+ channel = new MethodChannel(messenger, CHANNEL_HANDLER);
+ channel.setMethodCallHandler(this);
+ }
+
+ public void switchToMessenger(BinaryMessenger messenger) {
+ channel.setMethodCallHandler(null);
+ this.messenger = messenger;
+ channel = new MethodChannel(messenger, CHANNEL_HANDLER);
+ channel.setMethodCallHandler(this);
+ }
+
+ public void invokePendingMethods() {
+ for (MethodInvocation mi : methodInvocationQueue) {
+ channel.invokeMethod(mi.method, mi.arg, mi.result);
+ }
+ methodInvocationQueue.clear();
+ }
+
+ @Override
+ public void onLoadChildren(final String parentMediaId, final MediaBrowserServiceCompat.Result<List<MediaBrowserCompat.MediaItem>> result, Bundle options) {
+ if (audioHandlerInterface != null) {
+ Map<String, Object> args = new HashMap<>();
+ args.put("parentMediaId", parentMediaId);
+ args.put("options", bundleToMap(options));
+ audioHandlerInterface.invokeMethod("getChildren", args, new MethodChannel.Result() {
+ @Override
+ public void error(String errorCode, String errorMessage, Object errorDetails) {
+ result.sendError(new Bundle());
+ }
+
+ @Override
+ public void notImplemented() {
+ result.sendError(new Bundle());
+ }
+
+ @Override
+ public void success(Object obj) {
+ Map<?, ?> response = (Map<?, ?>)obj;
+ @SuppressWarnings("unchecked") List<Map<?, ?>> rawMediaItems = (List<Map<?, ?>>)response.get("children");
+ List<MediaBrowserCompat.MediaItem> mediaItems = new ArrayList<>();
+ for (Map<?, ?> rawMediaItem : rawMediaItems) {
+ mediaItems.add(rawToMediaItem(rawMediaItem));
+ }
+ result.sendResult(mediaItems);
+ }
+ });
+ }
+ result.detach();
+ }
+
+ @Override
+ public void onLoadItem(String itemId, final MediaBrowserServiceCompat.Result<MediaBrowserCompat.MediaItem> result) {
+ if (audioHandlerInterface != null) {
+ Map<String, Object> args = new HashMap<>();
+ args.put("mediaId", itemId);
+
+ audioHandlerInterface.invokeMethod("getMediaItem", args, new MethodChannel.Result() {
+ @Override
+ public void error(String errorCode, String errorMessage, Object errorDetails) {
+ result.sendError(new Bundle());
+ }
+
+ @Override
+ public void notImplemented() {
+ result.sendError(new Bundle());
+ }
+
+ @Override
+ public void success(Object obj) {
+ Map<?, ?> response = (Map<?, ?>)obj;
+ Map<?, ?> rawMediaItem = (Map<?, ?>)response.get("mediaItem");
+ if (rawMediaItem != null) {
+ MediaBrowserCompat.MediaItem mediaItem = rawToMediaItem(rawMediaItem);
+ result.sendResult(mediaItem);
+ } else {
+ result.sendResult(null);
+ }
+ }
+ });
+ }
+ result.detach();
+ }
+
+ @Override
+ public void onSearch(String query, Bundle extras, final MediaBrowserServiceCompat.Result<List<MediaBrowserCompat.MediaItem>> result) {
+ if (audioHandlerInterface != null) {
+ Map<String, Object> args = new HashMap<>();
+ args.put("query", query);
+ args.put("extras", bundleToMap(extras));
+ audioHandlerInterface.invokeMethod("search", args, new MethodChannel.Result() {
+ @Override
+ public void error(String errorCode, String errorMessage, Object errorDetails) {
+ result.sendError(new Bundle());
+ }
+
+ @Override
+ public void notImplemented() {
+ result.sendError(new Bundle());
+ }
+
+ @Override
+ public void success(Object obj) {
+ Map<?, ?> response = (Map<?, ?>)obj;
+ @SuppressWarnings("unchecked") List<Map<?, ?>> rawMediaItems = (List<Map<?, ?>>)response.get("mediaItems");
+ List<MediaBrowserCompat.MediaItem> mediaItems = new ArrayList<>();
+ for (Map<?, ?> rawMediaItem : rawMediaItems) {
+ mediaItems.add(rawToMediaItem(rawMediaItem));
+ }
+ result.sendResult(mediaItems);
+ }
+ });
+ }
+ result.detach();
+ }
+
+ @Override
+ public void onClick(MediaButton mediaButton) {
+ invokeMethod("click", mapOf("button", mediaButton.ordinal()));
+ }
+
+ @Override
+ public void onPause() {
+ invokeMethod("pause", mapOf());
+ }
+
+ @Override
+ public void onPrepare() {
+ invokeMethod("prepare", mapOf());
+ }
+
+ @Override
+ public void onPrepareFromMediaId(String mediaId, Bundle extras) {
+ invokeMethod("prepareFromMediaId", mapOf(
+ "mediaId", mediaId,
+ "extras", bundleToMap(extras)));
+ }
+
+ @Override
+ public void onPrepareFromSearch(String query, Bundle extras) {
+ invokeMethod("prepareFromSearch", mapOf(
+ "query", query,
+ "extras", bundleToMap(extras)));
+ }
+
+ @Override
+ public void onPrepareFromUri(Uri uri, Bundle extras) {
+ invokeMethod("prepareFromUri", mapOf(
+ "uri", uri.toString(),
+ "extras", bundleToMap(extras)));
+ }
+
+ @Override
+ public void onPlay() {
+ invokeMethod("play", mapOf());
+ }
+
+ @Override
+ public void onPlayFromMediaId(String mediaId, Bundle extras) {
+ invokeMethod("playFromMediaId", mapOf(
+ "mediaId", mediaId,
+ "extras", bundleToMap(extras)));
+ }
+
+ @Override
+ public void onPlayFromSearch(String query, Bundle extras) {
+ invokeMethod("playFromSearch", mapOf(
+ "query", query,
+ "extras", bundleToMap(extras)));
+ }
+
+ @Override
+ public void onPlayFromUri(Uri uri, Bundle extras) {
+ invokeMethod("playFromUri", mapOf(
+ "uri", uri.toString(),
+ "extras", bundleToMap(extras)));
+ }
+
+ @Override
+ public void onPlayMediaItem(MediaMetadataCompat metadata) {
+ invokeMethod("playMediaItem", mapOf("mediaItem", mediaMetadata2raw(metadata)));
+ }
+
+ @Override
+ public void onStop() {
+ invokeMethod("stop", mapOf());
+ }
+
+ @Override
+ public void onAddQueueItem(MediaMetadataCompat metadata) {
+ invokeMethod("addQueueItem", mapOf("mediaItem", mediaMetadata2raw(metadata)));
+ }
+
+ @Override
+ public void onAddQueueItemAt(MediaMetadataCompat metadata, int index) {
+ invokeMethod("insertQueueItem", mapOf(
+ "mediaItem", mediaMetadata2raw(metadata),
+ "index", index));
+ }
+
+ @Override
+ public void onRemoveQueueItem(MediaMetadataCompat metadata) {
+ invokeMethod("removeQueueItem", mapOf("mediaItem", mediaMetadata2raw(metadata)));
+ }
+
+ @Override
+ public void onRemoveQueueItemAt(int index) {
+ invokeMethod("removeQueueItemAt", mapOf("index", index));
+ }
+
+ @Override
+ public void onSkipToQueueItem(long queueItemId) {
+ invokeMethod("skipToQueueItem", mapOf("index", queueItemId));
+ }
+
+ @Override
+ public void onSkipToNext() {
+ invokeMethod("skipToNext", mapOf());
+ }
+
+ @Override
+ public void onSkipToPrevious() {
+ invokeMethod("skipToPrevious", mapOf());
+ }
+
+ @Override
+ public void onFastForward() {
+ invokeMethod("fastForward", mapOf());
+ }
+
+ @Override
+ public void onRewind() {
+ invokeMethod("rewind", mapOf());
+ }
+
+ @Override
+ public void onSeekTo(long pos) {
+ invokeMethod("seek", mapOf("position", pos*1000));
+ }
+
+ @Override
+ public void onSetPlaybackSpeed(float speed) {
+ invokeMethod("setSpeed", mapOf("speed", speed));
+ }
+
+ @Override
+ public void onSetCaptioningEnabled(boolean enabled) {
+ invokeMethod("setCaptioningEnabled", mapOf("enabled", enabled));
+ }
+
+ @Override
+ public void onSetRepeatMode(int repeatMode) {
+ invokeMethod("setRepeatMode", mapOf("repeatMode", repeatMode));
+ }
+
+ @Override
+ public void onSetShuffleMode(int shuffleMode) {
+ invokeMethod("setShuffleMode", mapOf("shuffleMode", shuffleMode));
+ }
+
+ @Override
+ public void onCustomAction(String action, Bundle extras) {
+ invokeMethod("customAction", mapOf(
+ "name", action,
+ "extras", bundleToMap(extras)));
+ }
+
+ @Override
+ public void onSetRating(RatingCompat rating) {
+ invokeMethod("setRating", mapOf(
+ "rating", rating2raw(rating),
+ "extras", null));
+ }
+
+ @Override
+ public void onSetRating(RatingCompat rating, Bundle extras) {
+ invokeMethod("setRating", mapOf(
+ "rating", rating2raw(rating),
+ "extras", bundleToMap(extras)));
+ }
+
+ @Override
+ public void onSetVolumeTo(int volumeIndex) {
+ invokeMethod("androidSetRemoteVolume", mapOf("volumeIndex", volumeIndex));
+ }
+
+ @Override
+ public void onAdjustVolume(int direction) {
+ invokeMethod("androidAdjustRemoteVolume", mapOf("direction", direction));
+ }
+
+ @Override
+ public void onTaskRemoved() {
+ invokeMethod("onTaskRemoved", mapOf());
+ }
+
+ @Override
+ public void onClose() {
+ invokeMethod("onNotificationDeleted", mapOf());
+ }
+
+ @Override
+ public void onDestroy() {
+ disposeFlutterEngine();
+ }
+
+ @Override
+ public void onMethodCall(MethodCall call, Result result) {
+ try {
+ Map<?, ?> args = (Map<?, ?>)call.arguments;
+ switch (call.method) {
+ case "setMediaItem": {
+ Executors.newSingleThreadExecutor().execute(() -> {
+ try {
+ Map<?, ?> rawMediaItem = (Map<?, ?>)args.get("mediaItem");
+ MediaMetadataCompat mediaMetadata = createMediaMetadata(rawMediaItem);
+ AudioService.instance.setMetadata(mediaMetadata);
+ handler.post(() -> result.success(null));
+ } catch (Exception e) {
+ handler.post(() -> {
+ result.error("UNEXPECTED_ERROR", "Unexpected error", Log.getStackTraceString(e));
+ });
+ }
+ });
+ break;
+ }
+ case "setQueue": {
+ Executors.newSingleThreadExecutor().execute(() -> {
+ try {
+ @SuppressWarnings("unchecked") List<Map<?, ?>> rawQueue = (List<Map<?, ?>>) args.get("queue");
+ List<MediaSessionCompat.QueueItem> queue = raw2queue(rawQueue);
+ AudioService.instance.setQueue(queue);
+ handler.post(() -> result.success(null));
+ } catch (Exception e) {
+ handler.post(() -> {
+ result.error("UNEXPECTED_ERROR", "Unexpected error", Log.getStackTraceString(e));
+ });
+ }
+ });
+ break;
+ }
+ case "setState": {
+ Map<?, ?> stateMap = (Map<?, ?>)args.get("state");
+ AudioProcessingState processingState = AudioProcessingState.values()[(Integer)stateMap.get("processingState")];
+ boolean playing = (Boolean)stateMap.get("playing");
+ @SuppressWarnings("unchecked") List<Map<?, ?>> rawControls = (List<Map<?, ?>>)stateMap.get("controls");
+ @SuppressWarnings("unchecked") List<Object> compactActionIndexList = (List<Object>)stateMap.get("androidCompactActionIndices");
+ @SuppressWarnings("unchecked") List<Integer> rawSystemActions = (List<Integer>)stateMap.get("systemActions");
+ long position = getLong(stateMap.get("updatePosition"));
+ long bufferedPosition = getLong(stateMap.get("bufferedPosition"));
+ float speed = (float)((double)((Double)stateMap.get("speed")));
+ long updateTimeSinceEpoch = stateMap.get("updateTime") == null ? System.currentTimeMillis() : getLong(stateMap.get("updateTime"));
+ Integer errorCode = (Integer)stateMap.get("errorCode");
+ String errorMessage = (String)stateMap.get("errorMessage");
+ int repeatMode = (Integer)stateMap.get("repeatMode");
+ int shuffleMode = (Integer)stateMap.get("shuffleMode");
+ Long queueIndex = getLong(stateMap.get("queueIndex"));
+ boolean captioningEnabled = (Boolean)stateMap.get("captioningEnabled");
+
+ // On the flutter side, we represent the update time relative to the epoch.
+ // On the native side, we must represent the update time relative to the boot time.
+ long updateTimeSinceBoot = updateTimeSinceEpoch - bootTime;
+
+ List<MediaControl> actions = new ArrayList<>();
+ long actionBits = 0;
+ for (Map<?, ?> rawControl : rawControls) {
+ String resource = (String)rawControl.get("androidIcon");
+ String label = (String)rawControl.get("label");
+ long actionCode = 1 << ((Integer)rawControl.get("action"));
+ actionBits |= actionCode;
+ Map<?, ?> customActionMap = (Map<?, ?>)rawControl.get("customAction");
+ CustomMediaAction customAction = null;
+ if (customActionMap != null) {
+ String name = (String) customActionMap.get("name");
+ Map<?, ?> extras = (Map<?, ?>) customActionMap.get("extras");
+ customAction = new CustomMediaAction(name, extras);
+ }
+ actions.add(new MediaControl(resource, label, actionCode, customAction));
+ }
+ for (Integer rawSystemAction : rawSystemActions) {
+ long actionCode = 1 << rawSystemAction;
+ actionBits |= actionCode;
+ }
+ int[] compactActionIndices = null;
+ if (compactActionIndexList != null) {
+ compactActionIndices = new int[Math.min(AudioService.MAX_COMPACT_ACTIONS, compactActionIndexList.size())];
+ for (int i = 0; i < compactActionIndices.length; i++)
+ compactActionIndices[i] = (Integer)compactActionIndexList.get(i);
+ }
+ AudioService.instance.setState(
+ actions,
+ actionBits,
+ compactActionIndices,
+ processingState,
+ playing,
+ position,
+ bufferedPosition,
+ speed,
+ updateTimeSinceBoot,
+ errorCode,
+ errorMessage,
+ repeatMode,
+ shuffleMode,
+ captioningEnabled,
+ queueIndex);
+ result.success(null);
+ break;
+ }
+ case "setAndroidPlaybackInfo": {
+ Map<?, ?> playbackInfo = (Map<?, ?>)args.get("playbackInfo");
+ final int playbackType = (Integer)playbackInfo.get("playbackType");
+ final Integer volumeControlType = (Integer)playbackInfo.get("volumeControlType");
+ final Integer maxVolume = (Integer)playbackInfo.get("maxVolume");
+ final Integer volume = (Integer)playbackInfo.get("volume");
+ AudioService.instance.setPlaybackInfo(playbackType, volumeControlType, maxVolume, volume);
+ result.success(null);
+ break;
+ }
+ case "notifyChildrenChanged": {
+ String parentMediaId = (String)args.get("parentMediaId");
+ Map<?, ?> options = (Map<?, ?>)args.get("options");
+ AudioService.instance.notifyChildrenChanged(parentMediaId, mapToBundle(options));
+ result.success(null);
+ break;
+ }
+ case "androidForceEnableMediaButtons": {
+ // Just play a short amount of silence. This convinces Android
+ // that we are playing "real" audio so that it will route
+ // media buttons to us.
+ // See: https://issuetracker.google.com/issues/65344811
+ if (silenceAudioTrack == null) {
+ byte[] silence = new byte[2048];
+ // TODO: Uncomment this after moving to a minSdkVersion of 21.
+ /* AudioAttributes audioAttributes = new AudioAttributes.Builder() */
+ /* .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) */
+ /* .setUsage(AudioAttributes.USAGE_MEDIA) */
+ /* .build(); */
+ /* AudioFormat audioFormat = new AudioFormat.Builder() */
+ /* .setChannelMask(AudioFormat.CHANNEL_CONFIGURATION_MONO) */
+ /* .setEncoding(AudioFormat.ENCODING_PCM_8BIT) */
+ /* .setSampleRate(SILENCE_SAMPLE_RATE) */
+ /* .build(); */
+ /* silenceAudioTrack = new AudioTrack.Builder() */
+ /* .setAudioAttributes(audioAttributes) */
+ /* .setAudioFormat(audioFormat) */
+ /* .setBufferSizeInBytes(silence.length) */
+ /* .setTransferMode(AudioTrack.MODE_STATIC) */
+ /* .build(); */
+ @SuppressWarnings("deprecation")
+ final AudioTrack audioTrack = new AudioTrack(
+ AudioManager.STREAM_MUSIC,
+ SILENCE_SAMPLE_RATE,
+ AudioFormat.CHANNEL_CONFIGURATION_MONO,
+ AudioFormat.ENCODING_PCM_8BIT,
+ silence.length,
+ AudioTrack.MODE_STATIC);
+ silenceAudioTrack = audioTrack;
+ silenceAudioTrack.write(silence, 0, silence.length);
+ }
+ silenceAudioTrack.reloadStaticData();
+ silenceAudioTrack.play();
+ result.success(null);
+ break;
+ }
+ case "stopService": {
+ if (AudioService.instance != null) {
+ AudioService.instance.stop();
+ }
+ result.success(null);
+ break;
+ }
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ result.error(e.getMessage(), null, null);
+ }
+ }
+
+ @UiThread
+ public void invokeMethod(String method, Object arg) {
+ invokeMethod(method, arg, null);
+ }
+
+ @UiThread
+ public void invokeMethod(String method, Object arg, final Result result) {
+ if (flutterReady) {
+ channel.invokeMethod(method, arg, result);
+ } else {
+ methodInvocationQueue.add(new MethodInvocation(method, arg, result));
+ }
+ }
+
+ private void destroy() {
+ if (silenceAudioTrack != null)
+ silenceAudioTrack.release();
+ }
+ }
+
+ private static List<Map<?, ?>> mediaItems2raw(List<MediaBrowserCompat.MediaItem> mediaItems) {
+ List<Map<?, ?>> rawMediaItems = new ArrayList<>();
+ for (MediaBrowserCompat.MediaItem mediaItem : mediaItems) {
+ MediaDescriptionCompat description = mediaItem.getDescription();
+ MediaMetadataCompat mediaMetadata = AudioService.getMediaMetadata(description.getMediaId());
+ rawMediaItems.add(mediaMetadata2raw(mediaMetadata));
+ }
+ return rawMediaItems;
+ }
+
+ private static List<Map<?, ?>> queue2raw(List<MediaSessionCompat.QueueItem> queue) {
+ if (queue == null) return null;
+ List<Map<?, ?>> rawQueue = new ArrayList<>();
+ for (MediaSessionCompat.QueueItem queueItem : queue) {
+ MediaDescriptionCompat description = queueItem.getDescription();
+ MediaMetadataCompat mediaMetadata = AudioService.getMediaMetadata(description.getMediaId());
+ rawQueue.add(mediaMetadata2raw(mediaMetadata));
+ }
+ return rawQueue;
+ }
+
+ private static RatingCompat raw2rating(Map<?, ?> raw) {
+ if (raw == null) return null;
+ Integer type = (Integer)raw.get("type");
+ Object value = raw.get("value");
+ if (value != null) {
+ switch (type) {
+ case RatingCompat.RATING_3_STARS:
+ case RatingCompat.RATING_4_STARS:
+ case RatingCompat.RATING_5_STARS:
+ return RatingCompat.newStarRating(type, (int)value);
+ case RatingCompat.RATING_HEART:
+ return RatingCompat.newHeartRating((boolean)value);
+ case RatingCompat.RATING_PERCENTAGE:
+ return RatingCompat.newPercentageRating(((Double)value).floatValue());
+ case RatingCompat.RATING_THUMB_UP_DOWN:
+ return RatingCompat.newThumbRating((boolean)value);
+ default:
+ return RatingCompat.newUnratedRating(type);
+ }
+ } else {
+ return RatingCompat.newUnratedRating(type);
+ }
+ }
+
+ private static HashMap<String, Object> rating2raw(RatingCompat rating) {
+ HashMap<String, Object> raw = new HashMap<>();
+ raw.put("type", rating.getRatingStyle());
+ if (rating.isRated()) {
+ switch (rating.getRatingStyle()) {
+ case RatingCompat.RATING_3_STARS:
+ case RatingCompat.RATING_4_STARS:
+ case RatingCompat.RATING_5_STARS:
+ raw.put("value", rating.getStarRating());
+ break;
+ case RatingCompat.RATING_HEART:
+ raw.put("value", rating.hasHeart());
+ break;
+ case RatingCompat.RATING_PERCENTAGE:
+ raw.put("value", rating.getPercentRating());
+ break;
+ case RatingCompat.RATING_THUMB_UP_DOWN:
+ raw.put("value", rating.isThumbUp());
+ break;
+ case RatingCompat.RATING_NONE:
+ raw.put("value", null);
+ }
+ } else {
+ raw.put("value", null);
+ }
+ return raw;
+ }
+
+ private static String metadataToString(MediaMetadataCompat mediaMetadata, String key) {
+ CharSequence value = mediaMetadata.getText(key);
+ if (value != null)
+ return value.toString();
+ return null;
+ }
+
+ private static Map<?, ?> mediaMetadata2raw(MediaMetadataCompat mediaMetadata) {
+ if (mediaMetadata == null) return null;
+ MediaDescriptionCompat description = mediaMetadata.getDescription();
+ Map<String, Object> raw = new HashMap<>();
+ raw.put("id", description.getMediaId());
+ raw.put("title", metadataToString(mediaMetadata, MediaMetadataCompat.METADATA_KEY_TITLE));
+ raw.put("album", metadataToString(mediaMetadata, MediaMetadataCompat.METADATA_KEY_ALBUM));
+ if (description.getIconUri() != null)
+ raw.put("artUri", description.getIconUri().toString());
+ raw.put("artist", metadataToString(mediaMetadata, MediaMetadataCompat.METADATA_KEY_ARTIST));
+ raw.put("genre", metadataToString(mediaMetadata, MediaMetadataCompat.METADATA_KEY_GENRE));
+ if (mediaMetadata.containsKey(MediaMetadataCompat.METADATA_KEY_DURATION))
+ raw.put("duration", mediaMetadata.getLong(MediaMetadataCompat.METADATA_KEY_DURATION));
+ raw.put("playable", mediaMetadata.getLong("playable_long") != 0);
+ raw.put("displayTitle", metadataToString(mediaMetadata, MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE));
+ raw.put("displaySubtitle", metadataToString(mediaMetadata, MediaMetadataCompat.METADATA_KEY_DISPLAY_SUBTITLE));
+ raw.put("displayDescription", metadataToString(mediaMetadata, MediaMetadataCompat.METADATA_KEY_DISPLAY_DESCRIPTION));
+ if (mediaMetadata.containsKey(MediaMetadataCompat.METADATA_KEY_RATING)) {
+ raw.put("rating", rating2raw(mediaMetadata.getRating(MediaMetadataCompat.METADATA_KEY_RATING)));
+ }
+ Map<String, Object> extras = bundleToMap(mediaMetadata.getBundle());
+ if (extras.size() > 0) {
+ raw.put("extras", extras);
+ }
+ return raw;
+ }
+
+ private static MediaMetadataCompat createMediaMetadata(Map<?, ?> rawMediaItem) {
+ //noinspection unchecked
+ return AudioService.instance.createMediaMetadata(
+ (String)rawMediaItem.get("id"),
+ (String)rawMediaItem.get("title"),
+ (String)rawMediaItem.get("album"),
+ (String)rawMediaItem.get("artist"),
+ (String)rawMediaItem.get("genre"),
+ getLong(rawMediaItem.get("duration")),
+ (String)rawMediaItem.get("artUri"),
+ (Boolean)rawMediaItem.get("playable"),
+ (String)rawMediaItem.get("displayTitle"),
+ (String)rawMediaItem.get("displaySubtitle"),
+ (String)rawMediaItem.get("displayDescription"),
+ raw2rating((Map<?, ?>)rawMediaItem.get("rating")),
+ (Map<?, ?>)rawMediaItem.get("extras")
+ );
+ }
+
+ /**
+ * Propagate mediaItem extras passed from dart to the description. By default, when creating
+ * a MediaMetadataCompat object, it doesn't propagate all the extras to the MediaDescription
+ * instance it holds.
+ *
+ * @param description original description object
+ * @param extras extras map coming from dart
+ * @return description with added extras
+ */
+ private static MediaDescriptionCompat addExtrasToMediaDescription(MediaDescriptionCompat description, Map<?, ?> extras) {
+ if (extras == null || extras.isEmpty()) {
+ return description;
+ }
+ final Bundle extrasBundle = new Bundle();
+ if (description.getExtras() != null) {
+ extrasBundle.putAll(description.getExtras());
+ }
+ extrasBundle.putAll(mapToBundle(extras));
+ return new MediaDescriptionCompat.Builder()
+ .setTitle(description.getTitle())
+ .setSubtitle(description.getSubtitle())
+ .setDescription(description.getDescription())
+ .setIconBitmap(description.getIconBitmap())
+ .setIconUri(description.getIconUri())
+ .setMediaId(description.getMediaId())
+ .setMediaUri(description.getMediaUri())
+ .setExtras(extrasBundle).build();
+ }
+
+ private static MediaBrowserCompat.MediaItem rawToMediaItem(Map<?, ?> rawMediaItem) {
+ MediaMetadataCompat mediaMetadata = createMediaMetadata(rawMediaItem);
+ final MediaDescriptionCompat description = addExtrasToMediaDescription(mediaMetadata.getDescription(), (Map<?, ?>)rawMediaItem.get("extras"));
+ final Boolean playable = (Boolean)rawMediaItem.get("playable");
+ return new MediaBrowserCompat.MediaItem(description, playable ? MediaBrowserCompat.MediaItem.FLAG_PLAYABLE : MediaBrowserCompat.MediaItem.FLAG_BROWSABLE);
+ }
+
+ private static List<MediaSessionCompat.QueueItem> raw2queue(List<Map<?, ?>> rawQueue) {
+ List<MediaSessionCompat.QueueItem> queue = new ArrayList<>();
+ int i = 0;
+ for (Map<?, ?> rawMediaItem : rawQueue) {
+ MediaMetadataCompat mediaMetadata = createMediaMetadata(rawMediaItem);
+ MediaDescriptionCompat description = addExtrasToMediaDescription(mediaMetadata.getDescription(), (Map<?, ?>)rawMediaItem.get("extras"));
+ queue.add(new MediaSessionCompat.QueueItem(description, i));
+ i++;
+ }
+ return queue;
+ }
+
+ public static Long getLong(Object o) {
+ return (o == null || o instanceof Long) ? (Long)o : Long.valueOf((Integer) o);
+ }
+
+ public static Integer getInt(Object o) {
+ return (o == null || o instanceof Integer) ? (Integer)o : Integer.valueOf((int)((Long)o).longValue());
+ }
+
+ static Map<String, Object> bundleToMap(Bundle bundle) {
+ if (bundle == null) return null;
+ Map<String, Object> map = new HashMap<>();
+ for (String key : bundle.keySet()) {
+ // TODO: use typesafe version once SDK 33 is released.
+ @SuppressWarnings("deprecation")
+ Object value = bundle.getSerializable(key);
+ if (value != null) {
+ map.put(key, value);
+ }
+ }
+ return map;
+ }
+
+ static Bundle mapToBundle(Map<?, ?> map) {
+ if (map == null) return null;
+ final Bundle bundle = new Bundle();
+ for (Object key : map.keySet()) {
+ String skey = (String)key;
+ Object value = map.get(skey);
+ if (value instanceof Integer) bundle.putInt(skey, (Integer)value);
+ else if (value instanceof Long) bundle.putLong(skey, (Long)value);
+ else if (value instanceof Double) bundle.putDouble(skey, (Double)value);
+ else if (value instanceof Boolean) bundle.putBoolean(skey, (Boolean)value);
+ else if (value instanceof String) bundle.putString(skey, (String)value);
+ }
+ return bundle;
+ }
+
+ static Map<String, Object> mapOf(Object... args) {
+ Map<String, Object> map = new HashMap<>();
+ for (int i = 0; i < args.length; i += 2) {
+ map.put((String)args[i], args[i + 1]);
+ }
+ return map;
+ }
+
+ static class MethodInvocation {
+ public final String method;
+ public final Object arg;
+ public final Result result;
+
+ public MethodInvocation(String method, Object arg, Result result) {
+ this.method = method;
+ this.arg = arg;
+ this.result = result;
+ }
+ }
+}
diff --git a/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/CustomMediaAction.java b/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/CustomMediaAction.java
new file mode 100644
index 00000000..da942aa7
--- /dev/null
+++ b/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/CustomMediaAction.java
@@ -0,0 +1,27 @@
+package com.ryanheise.audioservice;
+
+import java.util.Map;
+import java.util.Objects;
+
+public class CustomMediaAction {
+ public final String name;
+ public final Map<?, ?> extras;
+
+ public CustomMediaAction(String name, Map<?, ?> extras) {
+ this.name = name;
+ this.extras = extras;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ CustomMediaAction that = (CustomMediaAction) o;
+ return name.equals(that.name) && Objects.equals(extras, that.extras);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(name, extras);
+ }
+}
diff --git a/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/MediaButton.java b/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/MediaButton.java
new file mode 100644
index 00000000..89d937f5
--- /dev/null
+++ b/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/MediaButton.java
@@ -0,0 +1,7 @@
+package com.ryanheise.audioservice;
+
+public enum MediaButton {
+ media,
+ next,
+ previous
+}
diff --git a/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/MediaButtonReceiver.java b/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/MediaButtonReceiver.java
new file mode 100644
index 00000000..e414381c
--- /dev/null
+++ b/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/MediaButtonReceiver.java
@@ -0,0 +1,19 @@
+package com.ryanheise.audioservice;
+
+import android.content.Context;
+import android.content.Intent;
+
+public class MediaButtonReceiver extends androidx.media.session.MediaButtonReceiver {
+ public static final String ACTION_NOTIFICATION_DELETE = "com.ryanheise.audioservice.intent.action.ACTION_NOTIFICATION_DELETE";
+
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ if (intent != null
+ && ACTION_NOTIFICATION_DELETE.equals(intent.getAction())
+ && AudioService.instance != null) {
+ AudioService.instance.handleDeleteNotification();
+ return;
+ }
+ super.onReceive(context, intent);
+ }
+}
diff --git a/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/MediaControl.java b/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/MediaControl.java
new file mode 100644
index 00000000..d78f7e99
--- /dev/null
+++ b/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/MediaControl.java
@@ -0,0 +1,27 @@
+package com.ryanheise.audioservice;
+
+import java.util.Objects;
+
+public class MediaControl {
+ public final String icon;
+ public final String label;
+ public final long actionCode;
+ public final CustomMediaAction customAction;
+
+ public MediaControl(String icon, String label, long actionCode, CustomMediaAction customAction) {
+ this.icon = icon;
+ this.label = label;
+ this.actionCode = actionCode;
+ this.customAction = customAction;
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (other instanceof MediaControl) {
+ MediaControl otherControl = (MediaControl)other;
+ return icon.equals(otherControl.icon) && label.equals(otherControl.label) && actionCode == otherControl.actionCode && Objects.equals(customAction, otherControl.customAction);
+ } else {
+ return false;
+ }
+ }
+}
diff --git a/packages/audio_service/android/src/main/res/drawable-hdpi/audio_service_fast_forward.png b/packages/audio_service/android/src/main/res/drawable-hdpi/audio_service_fast_forward.png
new file mode 100644
index 00000000..24d97839
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-hdpi/audio_service_fast_forward.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-hdpi/audio_service_fast_rewind.png b/packages/audio_service/android/src/main/res/drawable-hdpi/audio_service_fast_rewind.png
new file mode 100644
index 00000000..3b564bab
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-hdpi/audio_service_fast_rewind.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-hdpi/audio_service_pause.png b/packages/audio_service/android/src/main/res/drawable-hdpi/audio_service_pause.png
new file mode 100644
index 00000000..794f350d
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-hdpi/audio_service_pause.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-hdpi/audio_service_play_arrow.png b/packages/audio_service/android/src/main/res/drawable-hdpi/audio_service_play_arrow.png
new file mode 100644
index 00000000..84998dd6
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-hdpi/audio_service_play_arrow.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-hdpi/audio_service_skip_next.png b/packages/audio_service/android/src/main/res/drawable-hdpi/audio_service_skip_next.png
new file mode 100644
index 00000000..100237c5
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-hdpi/audio_service_skip_next.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-hdpi/audio_service_skip_previous.png b/packages/audio_service/android/src/main/res/drawable-hdpi/audio_service_skip_previous.png
new file mode 100644
index 00000000..7dd69775
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-hdpi/audio_service_skip_previous.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-hdpi/audio_service_stop.png b/packages/audio_service/android/src/main/res/drawable-hdpi/audio_service_stop.png
new file mode 100644
index 00000000..7494d030
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-hdpi/audio_service_stop.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-mdpi/audio_service_fast_forward.png b/packages/audio_service/android/src/main/res/drawable-mdpi/audio_service_fast_forward.png
new file mode 100644
index 00000000..f81de6fa
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-mdpi/audio_service_fast_forward.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-mdpi/audio_service_fast_rewind.png b/packages/audio_service/android/src/main/res/drawable-mdpi/audio_service_fast_rewind.png
new file mode 100644
index 00000000..7d1797e5
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-mdpi/audio_service_fast_rewind.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-mdpi/audio_service_pause.png b/packages/audio_service/android/src/main/res/drawable-mdpi/audio_service_pause.png
new file mode 100644
index 00000000..e2f63777
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-mdpi/audio_service_pause.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-mdpi/audio_service_play_arrow.png b/packages/audio_service/android/src/main/res/drawable-mdpi/audio_service_play_arrow.png
new file mode 100644
index 00000000..084d6f31
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-mdpi/audio_service_play_arrow.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-mdpi/audio_service_skip_next.png b/packages/audio_service/android/src/main/res/drawable-mdpi/audio_service_skip_next.png
new file mode 100644
index 00000000..13663f15
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-mdpi/audio_service_skip_next.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-mdpi/audio_service_skip_previous.png b/packages/audio_service/android/src/main/res/drawable-mdpi/audio_service_skip_previous.png
new file mode 100644
index 00000000..bca4c3a9
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-mdpi/audio_service_skip_previous.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-mdpi/audio_service_stop.png b/packages/audio_service/android/src/main/res/drawable-mdpi/audio_service_stop.png
new file mode 100644
index 00000000..413184ae
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-mdpi/audio_service_stop.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-xhdpi/audio_service_fast_forward.png b/packages/audio_service/android/src/main/res/drawable-xhdpi/audio_service_fast_forward.png
new file mode 100644
index 00000000..ceec9797
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-xhdpi/audio_service_fast_forward.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-xhdpi/audio_service_fast_rewind.png b/packages/audio_service/android/src/main/res/drawable-xhdpi/audio_service_fast_rewind.png
new file mode 100644
index 00000000..52c5e7c3
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-xhdpi/audio_service_fast_rewind.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-xhdpi/audio_service_pause.png b/packages/audio_service/android/src/main/res/drawable-xhdpi/audio_service_pause.png
new file mode 100644
index 00000000..04759eed
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-xhdpi/audio_service_pause.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-xhdpi/audio_service_play_arrow.png b/packages/audio_service/android/src/main/res/drawable-xhdpi/audio_service_play_arrow.png
new file mode 100644
index 00000000..7b9b221e
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-xhdpi/audio_service_play_arrow.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-xhdpi/audio_service_skip_next.png b/packages/audio_service/android/src/main/res/drawable-xhdpi/audio_service_skip_next.png
new file mode 100644
index 00000000..f8662731
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-xhdpi/audio_service_skip_next.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-xhdpi/audio_service_skip_previous.png b/packages/audio_service/android/src/main/res/drawable-xhdpi/audio_service_skip_previous.png
new file mode 100644
index 00000000..f5a741e9
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-xhdpi/audio_service_skip_previous.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-xhdpi/audio_service_stop.png b/packages/audio_service/android/src/main/res/drawable-xhdpi/audio_service_stop.png
new file mode 100644
index 00000000..f7d0bc90
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-xhdpi/audio_service_stop.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-xxhdpi/audio_service_fast_forward.png b/packages/audio_service/android/src/main/res/drawable-xxhdpi/audio_service_fast_forward.png
new file mode 100644
index 00000000..058b149c
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-xxhdpi/audio_service_fast_forward.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-xxhdpi/audio_service_fast_rewind.png b/packages/audio_service/android/src/main/res/drawable-xxhdpi/audio_service_fast_rewind.png
new file mode 100644
index 00000000..3f2bde87
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-xxhdpi/audio_service_fast_rewind.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-xxhdpi/audio_service_pause.png b/packages/audio_service/android/src/main/res/drawable-xxhdpi/audio_service_pause.png
new file mode 100644
index 00000000..4a58a391
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-xxhdpi/audio_service_pause.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-xxhdpi/audio_service_play_arrow.png b/packages/audio_service/android/src/main/res/drawable-xxhdpi/audio_service_play_arrow.png
new file mode 100644
index 00000000..4c3fc474
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-xxhdpi/audio_service_play_arrow.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-xxhdpi/audio_service_skip_next.png b/packages/audio_service/android/src/main/res/drawable-xxhdpi/audio_service_skip_next.png
new file mode 100644
index 00000000..ff679573
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-xxhdpi/audio_service_skip_next.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-xxhdpi/audio_service_skip_previous.png b/packages/audio_service/android/src/main/res/drawable-xxhdpi/audio_service_skip_previous.png
new file mode 100644
index 00000000..c4d858e6
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-xxhdpi/audio_service_skip_previous.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-xxhdpi/audio_service_stop.png b/packages/audio_service/android/src/main/res/drawable-xxhdpi/audio_service_stop.png
new file mode 100644
index 00000000..7f8775ae
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-xxhdpi/audio_service_stop.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-xxxhdpi/audio_service_fast_forward.png b/packages/audio_service/android/src/main/res/drawable-xxxhdpi/audio_service_fast_forward.png
new file mode 100644
index 00000000..6153646a
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-xxxhdpi/audio_service_fast_forward.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-xxxhdpi/audio_service_fast_rewind.png b/packages/audio_service/android/src/main/res/drawable-xxxhdpi/audio_service_fast_rewind.png
new file mode 100644
index 00000000..5de2f31e
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-xxxhdpi/audio_service_fast_rewind.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-xxxhdpi/audio_service_pause.png b/packages/audio_service/android/src/main/res/drawable-xxxhdpi/audio_service_pause.png
new file mode 100644
index 00000000..1d0ff1b0
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-xxxhdpi/audio_service_pause.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-xxxhdpi/audio_service_play_arrow.png b/packages/audio_service/android/src/main/res/drawable-xxxhdpi/audio_service_play_arrow.png
new file mode 100644
index 00000000..6fedb6fa
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-xxxhdpi/audio_service_play_arrow.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-xxxhdpi/audio_service_skip_next.png b/packages/audio_service/android/src/main/res/drawable-xxxhdpi/audio_service_skip_next.png
new file mode 100644
index 00000000..464a3cca
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-xxxhdpi/audio_service_skip_next.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-xxxhdpi/audio_service_skip_previous.png b/packages/audio_service/android/src/main/res/drawable-xxxhdpi/audio_service_skip_previous.png
new file mode 100644
index 00000000..fe0efaab
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-xxxhdpi/audio_service_skip_previous.png differ
diff --git a/packages/audio_service/android/src/main/res/drawable-xxxhdpi/audio_service_stop.png b/packages/audio_service/android/src/main/res/drawable-xxxhdpi/audio_service_stop.png
new file mode 100644
index 00000000..580c6237
Binary files /dev/null and b/packages/audio_service/android/src/main/res/drawable-xxxhdpi/audio_service_stop.png differ
diff --git a/packages/audio_service/darwin/audio_service.podspec b/packages/audio_service/darwin/audio_service.podspec
new file mode 100644
index 00000000..9a5ad987
--- /dev/null
+++ b/packages/audio_service/darwin/audio_service.podspec
@@ -0,0 +1,23 @@
+#
+# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
+#
+Pod::Spec.new do |s|
+ s.name = 'audio_service'
+ s.version = '0.0.1'
+ s.summary = 'Flutter plugin to play audio in the background while the screen is off.'
+ s.description = <<-DESC
+Flutter plugin to play audio in the background while the screen is off.
+ DESC
+ s.homepage = 'https://github.com/ryanheise/audio_service'
+ s.license = { :file => '../LICENSE' }
+ s.author = { 'Ryan Heise' => '[email protected]' }
+ s.source = { :path => '.' }
+ s.source_files = 'audio_service/Sources/audio_service/**/*.{h,m}'
+ s.public_header_files = 'audio_service/Sources/audio_service/include/**/*.h'
+ s.ios.dependency 'Flutter'
+ s.osx.dependency 'FlutterMacOS'
+ s.ios.deployment_target = '12.0'
+ s.osx.deployment_target = '10.14'
+ s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
+end
+
diff --git a/packages/audio_service/darwin/audio_service/Package.swift b/packages/audio_service/darwin/audio_service/Package.swift
new file mode 100644
index 00000000..df367852
--- /dev/null
+++ b/packages/audio_service/darwin/audio_service/Package.swift
@@ -0,0 +1,25 @@
+// swift-tools-version: 5.9
+// The swift-tools-version declares the minimum version of Swift required to build this package.
+
+import PackageDescription
+
+let package = Package(
+ name: "audio_service",
+ platforms: [
+ .iOS("12.0"),
+ .macOS("10.14")
+ ],
+ products: [
+ .library(name: "audio-service", targets: ["audio_service"])
+ ],
+ dependencies: [],
+ targets: [
+ .target(
+ name: "audio_service",
+ dependencies: [],
+ cSettings: [
+ .headerSearchPath("include/audio_service")
+ ]
+ )
+ ]
+)
diff --git a/packages/audio_service/darwin/audio_service/Sources/audio_service/AudioServicePlugin.m b/packages/audio_service/darwin/audio_service/Sources/audio_service/AudioServicePlugin.m
new file mode 100644
index 00000000..2878fe71
--- /dev/null
+++ b/packages/audio_service/darwin/audio_service/Sources/audio_service/AudioServicePlugin.m
@@ -0,0 +1,580 @@
+#import "./include/audio_service/AudioServicePlugin.h"
+#import <AVFoundation/AVFoundation.h>
+#import <MediaPlayer/MediaPlayer.h>
+
+// If you'd like to help, please see the TODO comments below, then open a
+// GitHub issue to announce your intention to work on a particular feature, and
+// submit a pull request. We have an open discussion over at issue #10 about
+// all things iOS if you'd like to discuss approaches or ask for input. Thank
+// you for your support!
+
+static NSHashTable<AudioServicePlugin *> *plugins = nil;
+static FlutterMethodChannel *handlerChannel = nil;
+static FlutterResult startResult = nil;
+static MPRemoteCommandCenter *commandCenter = nil;
+static NSMutableDictionary *mediaItem = nil;
+static long actionBits = 0;
+static NSMutableArray *commands;
+static BOOL _controlsUpdated = NO;
+static enum AudioProcessingState processingState = ApsIdle;
+static BOOL playing = NO;
+static NSNumber *position = nil;
+static NSNumber *bufferedPosition = nil;
+static NSNumber *updateTime = nil;
+static NSNumber *speed = nil;
+static NSNumber *repeatMode = nil;
+static NSNumber *shuffleMode = nil;
+static NSNumber *fastForwardInterval = nil;
+static NSNumber *rewindInterval = nil;
+static MPMediaItemArtwork* artwork = nil;
+static NSMutableDictionary *nowPlayingInfo = nil;
+
+@implementation AudioServicePlugin {
+ FlutterMethodChannel *_channel;
+}
+
++ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
+ @synchronized(self) {
+ if (!plugins) {
+ plugins = [NSHashTable weakObjectsHashTable];
+ }
+ AudioServicePlugin *instance = [[AudioServicePlugin alloc] initWithRegistrar:registrar];
+ [registrar addMethodCallDelegate:instance channel:instance.channel];
+ [plugins addObject:instance];
+ if (!handlerChannel) {
+ processingState = ApsIdle;
+ position = @(0);
+ bufferedPosition = @(0);
+ long long msSinceEpoch = (long long)([[NSDate date] timeIntervalSince1970] * 1000.0);
+ updateTime = [NSNumber numberWithLongLong: msSinceEpoch];
+ speed = [NSNumber numberWithDouble: 1.0];
+ repeatMode = @(0);
+ shuffleMode = @(0);
+ nowPlayingInfo = [NSMutableDictionary new];
+ handlerChannel = [FlutterMethodChannel
+ methodChannelWithName:@"com.ryanheise.audio_service.handler.methods"
+ binaryMessenger:[registrar messenger]];
+ [registrar addMethodCallDelegate:instance channel:handlerChannel];
+ }
+ }
+}
+
+- (instancetype)initWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
+ self = [super init];
+ NSAssert(self, @"super init cannot be nil");
+ _channel = [FlutterMethodChannel
+ methodChannelWithName:@"com.ryanheise.audio_service.client.methods"
+ binaryMessenger:[registrar messenger]];
+ return self;
+}
+
+- (FlutterMethodChannel *)channel {
+ return _channel;
+}
+
+- (void)invokeClientMethod:(NSString *)method arguments:(id _Nullable)arguments {
+ for (AudioServicePlugin *plugin in plugins) {
+ [plugin.channel invokeMethod:method arguments:arguments];
+ }
+}
+
+- (void)invokeClientMethod:(NSString *)method arguments:(id _Nullable)arguments result:(FlutterResult)result {
+ for (AudioServicePlugin *plugin in plugins) {
+ [plugin.channel invokeMethod:method arguments:arguments result:result];
+ }
+}
+
+- (void)activateCommandCenter {
+ //NSLog(@"### activateCommandCenter");
+ commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
+ commands = [NSMutableArray new];
+ [commands addObjectsFromArray:@[
+ commandCenter.stopCommand,
+ commandCenter.pauseCommand,
+ commandCenter.playCommand,
+ commandCenter.skipBackwardCommand,
+ commandCenter.previousTrackCommand,
+ commandCenter.nextTrackCommand,
+ commandCenter.skipForwardCommand,
+ [NSNull null],
+ [NSNull null], // changePlaybackPositionCommand, put below
+ commandCenter.togglePlayPauseCommand,
+ [NSNull null],
+ [NSNull null],
+ [NSNull null],
+ [NSNull null],
+ [NSNull null],
+ [NSNull null],
+ [NSNull null],
+ [NSNull null],
+ commandCenter.changeRepeatModeCommand,
+ [NSNull null],
+ [NSNull null],
+ commandCenter.changeShuffleModeCommand,
+ commandCenter.seekBackwardCommand,
+ commandCenter.seekForwardCommand,
+ commandCenter.changePlaybackRateCommand,
+ ]];
+ if (@available(iOS 9.1, macOS 10.12.2, *)) {
+ commands[8] = commandCenter.changePlaybackPositionCommand;
+ }
+ [commandCenter.changePlaybackRateCommand setEnabled:YES];
+ [commandCenter.togglePlayPauseCommand setEnabled:YES];
+ [commandCenter.togglePlayPauseCommand addTarget:self action:@selector(togglePlayPause:)];
+ // TODO: enable more commands
+ // Language options
+ if (@available(iOS 9.0, macOS 10.12.2, *)) {
+ [commandCenter.enableLanguageOptionCommand setEnabled:NO];
+ [commandCenter.disableLanguageOptionCommand setEnabled:NO];
+ }
+ // Rating
+ [commandCenter.ratingCommand setEnabled:NO];
+ // Feedback
+ [commandCenter.likeCommand setEnabled:NO];
+ [commandCenter.dislikeCommand setEnabled:NO];
+ [commandCenter.bookmarkCommand setEnabled:NO];
+}
+
+- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
+ if ([@"configure" isEqualToString:call.method]) {
+ NSDictionary *args = (NSDictionary *)call.arguments;
+ NSDictionary *configMap = (NSDictionary *)args[@"config"];
+ fastForwardInterval = configMap[@"fastForwardInterval"];
+ rewindInterval = configMap[@"rewindInterval"];
+ result(@{});
+ } else if ([@"setState" isEqualToString:call.method]) {
+ NSDictionary *args = (NSDictionary *)call.arguments;
+ NSDictionary *stateMap = (NSDictionary *)args[@"state"];
+ long long msSinceEpoch;
+ if (stateMap[@"updateTime"] != [NSNull null]) {
+ msSinceEpoch = [stateMap[@"updateTime"] longLongValue];
+ } else {
+ msSinceEpoch = (long long)([[NSDate date] timeIntervalSince1970] * 1000.0);
+ }
+ actionBits = 0;
+ NSArray *controlsArray = stateMap[@"controls"];
+ for (int i = 0; i < controlsArray.count; i++) {
+ NSDictionary *control = (NSDictionary *)controlsArray[i];
+ NSNumber *actionIndex = (NSNumber *)control[@"action"];
+ int actionCode = 1 << [actionIndex intValue];
+ actionBits |= actionCode;
+ }
+ NSArray *systemActionsArray = stateMap[@"systemActions"];
+ for (int i = 0; i < systemActionsArray.count; i++) {
+ NSNumber *actionIndex = (NSNumber *)systemActionsArray[i];
+ int actionCode = 1 << [actionIndex intValue];
+ actionBits |= actionCode;
+ }
+ processingState = [stateMap[@"processingState"] intValue];
+ BOOL oldPlaying = playing;
+ NSNumber *oldSpeed = speed;
+ NSNumber *oldPosition = position;
+ playing = [stateMap[@"playing"] boolValue];
+ position = stateMap[@"updatePosition"];
+ bufferedPosition = stateMap[@"bufferedPosition"];
+ speed = stateMap[@"speed"];
+ repeatMode = stateMap[@"repeatMode"];
+ shuffleMode = stateMap[@"shuffleMode"];
+ updateTime = [NSNumber numberWithLongLong: msSinceEpoch];
+ if (playing && !commandCenter) {
+#if TARGET_OS_IPHONE
+ [AVAudioSession sharedInstance];
+#endif
+ [self activateCommandCenter];
+ }
+ [self updateControls];
+ if (playing != oldPlaying ||
+ speed.doubleValue != oldSpeed.doubleValue ||
+ position.longLongValue != oldPosition.longLongValue) {
+ [self updateNowPlayingInfo];
+ }
+ result(@{});
+ } else if ([@"setQueue" isEqualToString:call.method]) {
+ result(@{});
+ } else if ([@"setMediaItem" isEqualToString:call.method]) {
+ NSDictionary *args = (NSDictionary *)call.arguments;
+ mediaItem = args[@"mediaItem"];
+ NSString* artUri = mediaItem[@"artUri"];
+ artwork = nil;
+ if (![artUri isEqual: [NSNull null]]) {
+ NSString* artCacheFilePath = (NSString *)[NSNull null];
+ NSDictionary* extras = mediaItem[@"extras"];
+ if (![extras isEqual: [NSNull null]]) {
+ artCacheFilePath = extras[@"artCacheFile"];
+ }
+ if (![artCacheFilePath isEqual: [NSNull null]]) {
+#if TARGET_OS_IPHONE
+ UIImage* artImage = [UIImage imageWithContentsOfFile:artCacheFilePath];
+#else
+ NSImage* artImage = [[NSImage alloc] initWithContentsOfFile:artCacheFilePath];
+#endif
+ if (artImage != nil) {
+#if TARGET_OS_IPHONE
+ artwork = [[MPMediaItemArtwork alloc] initWithImage: artImage];
+#else
+ artwork = [[MPMediaItemArtwork alloc] initWithBoundsSize:artImage.size requestHandler:^NSImage* _Nonnull(CGSize aSize) {
+ return artImage;
+ }];
+#endif
+ }
+ }
+ }
+ [self updateNowPlayingInfo];
+ result(@{});
+ } else if ([@"setPlaybackInfo" isEqualToString:call.method]) {
+ result(@{});
+ } else if ([@"notifyChildrenChanged" isEqualToString:call.method]) {
+ result(@{});
+ } else if ([@"androidForceEnableMediaButtons" isEqualToString:call.method]) {
+ result(@{});
+ } else if ([@"stopService" isEqualToString:call.method]) {
+ [commandCenter.changePlaybackRateCommand setEnabled:NO];
+ [commandCenter.togglePlayPauseCommand setEnabled:NO];
+ [commandCenter.togglePlayPauseCommand removeTarget:nil];
+ [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = nil;
+ processingState = ApsIdle;
+ actionBits = 0;
+ [self updateControls];
+ _controlsUpdated = NO;
+ startResult = nil;
+ commandCenter = nil;
+ result(@{});
+ }
+}
+
+- (MPRemoteCommandHandlerStatus) play: (MPRemoteCommandEvent *) event {
+ //NSLog(@"play");
+ [handlerChannel invokeMethod:@"play" arguments:@{}];
+ return MPRemoteCommandHandlerStatusSuccess;
+}
+
+- (MPRemoteCommandHandlerStatus) pause: (MPRemoteCommandEvent *) event {
+ //NSLog(@"pause");
+ [handlerChannel invokeMethod:@"pause" arguments:@{}];
+ return MPRemoteCommandHandlerStatusSuccess;
+}
+
+- (BOOL)updateNowPlayingField:(NSString *)field value:(id)value {
+ if (![value isEqual:nowPlayingInfo[field]]) {
+ if (value != nil && value != [NSNull null]) {
+ //NSLog(@"### %@ = '%@'", field, value);
+ nowPlayingInfo[field] = value;
+ } else {
+ //NSLog(@"### %@ = nil", field);
+ [nowPlayingInfo removeObjectForKey:field];
+ }
+ return YES;
+ }
+ return NO;
+}
+
+- (void) updateNowPlayingInfo {
+ BOOL updated = NO;
+ if (mediaItem) {
+ updated |= [self updateNowPlayingField:MPMediaItemPropertyTitle value:mediaItem[@"title"]];
+ updated |= [self updateNowPlayingField:MPMediaItemPropertyAlbumTitle value:mediaItem[@"album"]];
+ updated |= [self updateNowPlayingField:MPMediaItemPropertyArtist value:mediaItem[@"artist"]];
+ NSNumber *duration = mediaItem[@"duration"];
+ if (duration == (id)[NSNull null]) duration = @(0);
+ updated |= [self updateNowPlayingField:MPMediaItemPropertyPlaybackDuration value:([NSNumber numberWithDouble: ([duration doubleValue] / 1000)])];
+ if (@available(iOS 3.0, macOS 10.13.2, *)) {
+ updated |= [self updateNowPlayingField:MPMediaItemPropertyArtwork value:artwork];
+ }
+ }
+
+ if (@available(iOS 10.0, macOS 10.12.2, *)) {
+ updated |= [self updateNowPlayingField:MPNowPlayingInfoPropertyMediaType value:@(MPNowPlayingInfoMediaTypeAudio)];
+ }
+ updated |= [self updateNowPlayingField:MPNowPlayingInfoPropertyPlaybackRate value:(playing ? speed : [NSNumber numberWithDouble: 0.0])];
+ updated |= [self updateNowPlayingField:MPNowPlayingInfoPropertyDefaultPlaybackRate value:(playing ? speed : [NSNumber numberWithDouble: 0.0])];
+ updated |= [self updateNowPlayingField:MPNowPlayingInfoPropertyElapsedPlaybackTime value:[NSNumber numberWithDouble:([position doubleValue] / 1000)]];
+ MPNowPlayingInfoCenter *center = [MPNowPlayingInfoCenter defaultCenter];
+ // playbackState is available on iOS 13+ and macOS 10.12.2+. Upstream 0.18.18
+ // wraps this in `#if TARGET_OS_OSX`, leaving it unset on iOS — and without
+ // an explicit .paused signal, iOS dismisses the now-playing entry (and
+ // Dynamic Island) a few seconds after pause, then suspends the app. Setting
+ // it on iOS too keeps the entry persistent like Apple Podcasts.
+ if (@available(iOS 13.0, macOS 10.12.2, *)) {
+ center.playbackState = playing ? MPNowPlayingPlaybackStatePlaying : MPNowPlayingPlaybackStatePaused;
+ }
+ if (@available(iOS 10.0, macOS 10.12.2, *)) {
+ updated |= [self updateNowPlayingField:MPNowPlayingInfoPropertyIsLiveStream value:mediaItem[@"isLive"]];
+ }
+ if (updated) {
+ //NSLog(@"### updating nowPlayingInfo");
+ center.nowPlayingInfo = nowPlayingInfo;
+ }
+
+ // TODO: List of all unused "nowPlayingInfo" keys, we might want to use these at some point:
+ //
+ // * MPNowPlayingInfoCollectionIdentifier
+ // * MPNowPlayingInfoPropertyAvailableLanguageOptions
+ // * MPNowPlayingInfoPropertyAssetURL
+ // * MPNowPlayingInfoPropertyChapterCount
+ // * MPNowPlayingInfoPropertyChapterNumber
+ // * MPNowPlayingInfoPropertyCurrentLanguageOptions
+ // * MPNowPlayingInfoPropertyDefaultPlaybackRate
+ // * MPNowPlayingInfoPropertyCurrentPlaybackDate
+ // * MPNowPlayingInfoPropertyExternalContentIdentifier
+ // * MPNowPlayingInfoPropertyExternalUserProfileIdentifier
+ // * MPNowPlayingInfoPropertyPlaybackProgress
+ // * MPNowPlayingInfoPropertyPlaybackQueueCount
+ // * MPNowPlayingInfoPropertyPlaybackQueueIndex
+ // * MPNowPlayingInfoPropertyServiceIdentifier
+}
+
+- (void) updateControls {
+ if (!commandCenter) return;
+ for (enum MediaAction action = AStop; action <= ASetSpeed; action++) {
+ [self updateControl:action];
+ }
+ _controlsUpdated = YES;
+}
+
+- (void) updateControl:(enum MediaAction)action {
+ MPRemoteCommand *command = commands[action];
+ if (command == (id)[NSNull null]) return;
+ // Shift the actionBits right until the least significant bit is the tested action bit, and AND that with a 1 at the same position.
+ // All bytes become 0, other than the tested action bit, which will be 0 or 1 according to its status in the actionBits long.
+ BOOL enable = ((actionBits >> action) & 1);
+ if (_controlsUpdated && enable == command.enabled) return;
+ //NSLog(@"## updateControl %@ enable=%@", @(action), @(enable));
+ [command setEnabled:enable];
+ switch (action) {
+ case AStop:
+ if (enable) {
+ [commandCenter.stopCommand addTarget:self action:@selector(stop:)];
+ } else {
+ [commandCenter.stopCommand removeTarget:nil];
+ }
+ break;
+ case APause:
+ if (enable) {
+ [commandCenter.pauseCommand addTarget:self action:@selector(pause:)];
+ } else {
+ [commandCenter.pauseCommand removeTarget:nil];
+ }
+ break;
+ case APlay:
+ if (enable) {
+ [commandCenter.playCommand addTarget:self action:@selector(play:)];
+ } else {
+ [commandCenter.playCommand removeTarget:nil];
+ }
+ break;
+ case ARewind:
+ if (rewindInterval.integerValue > 0) {
+ if (enable) {
+ [commandCenter.skipBackwardCommand addTarget: self action:@selector(skipBackward:)];
+ int rewindIntervalInSeconds = [rewindInterval intValue]/1000;
+ NSNumber *rewindIntervalInSec = [NSNumber numberWithInt: rewindIntervalInSeconds];
+ commandCenter.skipBackwardCommand.preferredIntervals = @[rewindIntervalInSec];
+ } else {
+ [commandCenter.skipBackwardCommand removeTarget:nil];
+ }
+ }
+ break;
+ case ASkipToPrevious:
+ if (enable) {
+ [commandCenter.previousTrackCommand addTarget:self action:@selector(previousTrack:)];
+ } else {
+ [commandCenter.previousTrackCommand removeTarget:nil];
+ }
+ break;
+ case ASkipToNext:
+ if (enable) {
+ [commandCenter.nextTrackCommand addTarget:self action:@selector(nextTrack:)];
+ } else {
+ [commandCenter.nextTrackCommand removeTarget:nil];
+ }
+ break;
+ case AFastForward:
+ if (fastForwardInterval.integerValue > 0) {
+ if (enable) {
+ [commandCenter.skipForwardCommand addTarget: self action:@selector(skipForward:)];
+ int fastForwardIntervalInSeconds = [fastForwardInterval intValue]/1000;
+ NSNumber *fastForwardIntervalInSec = [NSNumber numberWithInt: fastForwardIntervalInSeconds];
+ commandCenter.skipForwardCommand.preferredIntervals = @[fastForwardIntervalInSec];
+ } else {
+ [commandCenter.skipForwardCommand removeTarget:nil];
+ }
+ }
+ break;
+ case ASetRating:
+ // TODO:
+ // commandCenter.ratingCommand
+ // commandCenter.dislikeCommand
+ // commandCenter.bookmarkCommand
+ break;
+ case ASeekTo:
+ if (@available(iOS 9.1, macOS 10.12.2, *)) {
+ if (enable) {
+ [commandCenter.changePlaybackPositionCommand addTarget:self action:@selector(changePlaybackPosition:)];
+ } else {
+ [commandCenter.changePlaybackPositionCommand removeTarget:nil];
+ }
+ }
+ break;
+ case APlayPause:
+ // Automatically enabled.
+ break;
+ case ASetRepeatMode:
+ if (enable) {
+ [commandCenter.changeRepeatModeCommand addTarget:self action:@selector(changeRepeatMode:)];
+ } else {
+ [commandCenter.changeRepeatModeCommand removeTarget:nil];
+ }
+ break;
+ case ASetShuffleMode:
+ if (enable) {
+ [commandCenter.changeShuffleModeCommand addTarget:self action:@selector(changeShuffleMode:)];
+ } else {
+ [commandCenter.changeShuffleModeCommand removeTarget:nil];
+ }
+ break;
+ case ASeekBackward:
+ if (enable) {
+ [commandCenter.seekBackwardCommand addTarget:self action:@selector(seekBackward:)];
+ } else {
+ [commandCenter.seekBackwardCommand removeTarget:nil];
+ }
+ break;
+ case ASeekForward:
+ if (enable) {
+ [commandCenter.seekForwardCommand addTarget:self action:@selector(seekForward:)];
+ } else {
+ [commandCenter.seekForwardCommand removeTarget:nil];
+ }
+ break;
+ case ASetSpeed:
+ if (enable) {
+// [commandCenter.changePlaybackRateCommand setSupportedPlaybackRates:@[@(1),@(1.5),@(2)]]
+ [commandCenter.changePlaybackRateCommand addTarget:self action:@selector(changePlaybackRate:)];
+ } else {
+ [commandCenter.changePlaybackRateCommand removeTarget:nil];
+ }
+ break;
+ default:
+ break;
+ }
+}
+
+- (MPRemoteCommandHandlerStatus) togglePlayPause: (MPRemoteCommandEvent *) event {
+ //NSLog(@"togglePlayPause");
+ [handlerChannel invokeMethod:@"click" arguments:@{
+ @"button":@(0)
+ }];
+ return MPRemoteCommandHandlerStatusSuccess;
+}
+
+- (MPRemoteCommandHandlerStatus) stop: (MPRemoteCommandEvent *) event {
+ //NSLog(@"stop");
+ [handlerChannel invokeMethod:@"stop" arguments:@{}];
+ return MPRemoteCommandHandlerStatusSuccess;
+}
+
+- (MPRemoteCommandHandlerStatus) nextTrack: (MPRemoteCommandEvent *) event {
+ //NSLog(@"nextTrack");
+ [handlerChannel invokeMethod:@"skipToNext" arguments:@{}];
+ return MPRemoteCommandHandlerStatusSuccess;
+}
+
+- (MPRemoteCommandHandlerStatus) previousTrack: (MPRemoteCommandEvent *) event {
+ //NSLog(@"previousTrack");
+ [handlerChannel invokeMethod:@"skipToPrevious" arguments:@{}];
+ return MPRemoteCommandHandlerStatusSuccess;
+}
+
+- (MPRemoteCommandHandlerStatus) changePlaybackPosition: (MPChangePlaybackPositionCommandEvent *) event {
+ //NSLog(@"changePlaybackPosition");
+ [handlerChannel invokeMethod:@"seek" arguments: @{
+ @"position":@((long long) (event.positionTime * 1000000.0))
+ }];
+ return MPRemoteCommandHandlerStatusSuccess;
+}
+
+- (MPRemoteCommandHandlerStatus) skipForward: (MPRemoteCommandEvent *) event {
+ //NSLog(@"skipForward");
+ [handlerChannel invokeMethod:@"fastForward" arguments:@{}];
+ return MPRemoteCommandHandlerStatusSuccess;
+}
+
+- (MPRemoteCommandHandlerStatus) skipBackward: (MPRemoteCommandEvent *) event {
+ //NSLog(@"skipBackward");
+ [handlerChannel invokeMethod:@"rewind" arguments:@{}];
+ return MPRemoteCommandHandlerStatusSuccess;
+}
+
+- (MPRemoteCommandHandlerStatus) seekForward: (MPSeekCommandEvent *) event {
+ //NSLog(@"seekForward");
+ BOOL begin = event.type == MPSeekCommandEventTypeBeginSeeking;
+ [handlerChannel invokeMethod:@"seekForward" arguments:@{
+ @"begin":@(begin)
+ }];
+ return MPRemoteCommandHandlerStatusSuccess;
+}
+
+- (MPRemoteCommandHandlerStatus) seekBackward: (MPSeekCommandEvent *) event {
+ //NSLog(@"seekBackward");
+ BOOL begin = event.type == MPSeekCommandEventTypeBeginSeeking;
+ [handlerChannel invokeMethod:@"seekBackward" arguments:@{
+ @"begin":@(begin)
+ }];
+ return MPRemoteCommandHandlerStatusSuccess;
+}
+
+- (MPRemoteCommandHandlerStatus) changeRepeatMode: (MPChangeRepeatModeCommandEvent *) event {
+ //NSLog(@"changeRepeatMode");
+ int modeIndex;
+ switch (event.repeatType) {
+ case MPRepeatTypeOff:
+ modeIndex = 0;
+ break;
+ case MPRepeatTypeOne:
+ modeIndex = 1;
+ break;
+ // MPRepeatTypeAll
+ default:
+ modeIndex = 2;
+ break;
+ }
+ [handlerChannel invokeMethod:@"setRepeatMode" arguments:@{
+ @"repeatMode":@(modeIndex)
+ }];
+ return MPRemoteCommandHandlerStatusSuccess;
+}
+
+- (MPRemoteCommandHandlerStatus) changePlaybackRate: (MPChangePlaybackRateCommandEvent *) event {
+ //NSLog(@"changePlaybackRate");
+ [handlerChannel invokeMethod:@"setSpeed" arguments:@{
+ @"speed":@(event.playbackRate)
+ }];
+ return MPRemoteCommandHandlerStatusSuccess;
+}
+
+- (MPRemoteCommandHandlerStatus) changeShuffleMode: (MPChangeShuffleModeCommandEvent *) event {
+ //NSLog(@"changeShuffleMode");
+ int modeIndex;
+ switch (event.shuffleType) {
+ case MPShuffleTypeOff:
+ modeIndex = 0;
+ break;
+ case MPShuffleTypeItems:
+ modeIndex = 1;
+ break;
+ // MPShuffleTypeCollections
+ default:
+ modeIndex = 2;
+ break;
+ }
+ [handlerChannel invokeMethod:@"setShuffleMode" arguments:@{
+ @"shuffleMode":@(modeIndex)
+ }];
+ return MPRemoteCommandHandlerStatusSuccess;
+}
+
+- (void) dealloc {
+ [[NSNotificationCenter defaultCenter] removeObserver:self];
+}
+
+@end
diff --git a/packages/audio_service/darwin/audio_service/Sources/audio_service/include/audio_service/AudioServicePlugin.h b/packages/audio_service/darwin/audio_service/Sources/audio_service/include/audio_service/AudioServicePlugin.h
new file mode 100644
index 00000000..3f704397
--- /dev/null
+++ b/packages/audio_service/darwin/audio_service/Sources/audio_service/include/audio_service/AudioServicePlugin.h
@@ -0,0 +1,50 @@
+#import <AVFoundation/AVFoundation.h>
+#if TARGET_OS_OSX
+#import <FlutterMacOS/FlutterMacOS.h>
+#else
+#import <Flutter/Flutter.h>
+#endif
+
+@interface AudioServicePlugin : NSObject<FlutterPlugin>
+
+@property (readonly, nonatomic) FlutterMethodChannel *channel;
+
+@end
+
+enum AudioProcessingState {
+ ApsIdle,
+ ApsLoading,
+ ApsBuffering,
+ ApsReady,
+ ApsCompleted,
+ ApsError
+};
+
+enum MediaAction {
+ AStop,
+ APause,
+ APlay,
+ ARewind,
+ ASkipToPrevious,
+ ASkipToNext,
+ AFastForward,
+ ASetRating,
+ ASeekTo,
+ APlayPause,
+ APlayFromMediaId,
+ APlayFromSearch,
+ ASkipToQueueItem,
+ APlayFromUri,
+ APrepare,
+ APrepareFromMediaId,
+ APrepareFromSearch,
+ APrepareFromUri,
+ ASetRepeatMode,
+ ASetShuffleModeEnabled, // deprecated
+ ASetCaptioningEnabled,
+ ASetShuffleMode,
+ // iOS/macOS-specific
+ ASeekBackward,
+ ASeekForward,
+ ASetSpeed,
+};
diff --git a/packages/audio_service/example/README.md b/packages/audio_service/example/README.md
new file mode 100644
index 00000000..17772442
--- /dev/null
+++ b/packages/audio_service/example/README.md
@@ -0,0 +1,8 @@
+# audio_service_example
+
+[This example](https://github.com/ryanheise/audio_service/blob/master/example/lib/main.dart) demonstrates how to play an audio file or text-to-speech in the background.
+
+## Getting Started
+
+For help getting started with Flutter, view our online
+[documentation](https://flutter.io/).
diff --git a/packages/audio_service/example/android/app/build.gradle b/packages/audio_service/example/android/app/build.gradle
new file mode 100644
index 00000000..52a76e37
--- /dev/null
+++ b/packages/audio_service/example/android/app/build.gradle
@@ -0,0 +1,52 @@
+plugins {
+ id "com.android.application"
+ id "kotlin-android"
+ // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
+ id "dev.flutter.flutter-gradle-plugin"
+}
+
+android {
+ namespace = "com.ryanheise.audioserviceexample"
+ compileSdk = flutter.compileSdkVersion
+
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_11
+ targetCompatibility = JavaVersion.VERSION_11
+ }
+
+ kotlinOptions {
+ jvmTarget = JavaVersion.VERSION_11
+ }
+
+ defaultConfig {
+ applicationId "com.ryanheise.audioserviceexample"
+ minSdk = flutter.minSdkVersion
+ targetSdk = flutter.targetSdkVersion
+ versionCode = flutter.versionCode
+ versionName = flutter.versionName
+ }
+
+ buildTypes {
+ release {
+ // TODO: Add your own signing config for the release build.
+ // Signing with the debug keys for now, so `flutter run --release` works.
+ signingConfig signingConfigs.debug
+ shrinkResources true
+ }
+ }
+
+ lint {
+ disable = ["InvalidPackage"]
+ }
+}
+
+flutter {
+ source '../..'
+}
+
+dependencies {
+ testImplementation 'junit:junit:4.12'
+ androidTestImplementation 'androidx.test:runner:1.1.1'
+ androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
+ //debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.4'
+}
diff --git a/packages/audio_service/example/android/app/src/debug/AndroidManifest.xml b/packages/audio_service/example/android/app/src/debug/AndroidManifest.xml
new file mode 100644
index 00000000..f880684a
--- /dev/null
+++ b/packages/audio_service/example/android/app/src/debug/AndroidManifest.xml
@@ -0,0 +1,6 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+ <!-- Flutter needs it to communicate with the running application
+ to allow setting breakpoints, to provide hot reload, etc.
+ -->
+ <uses-permission android:name="android.permission.INTERNET"/>
+</manifest>
diff --git a/packages/audio_service/example/android/app/src/main/AndroidManifest.xml b/packages/audio_service/example/android/app/src/main/AndroidManifest.xml
new file mode 100644
index 00000000..048ba94f
--- /dev/null
+++ b/packages/audio_service/example/android/app/src/main/AndroidManifest.xml
@@ -0,0 +1,67 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:tools="http://schemas.android.com/tools">
+
+ <uses-permission android:name="android.permission.INTERNET"/>
+ <uses-permission android:name="android.permission.WAKE_LOCK"/>
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"/>
+
+ <!-- For example_android_songs example -->
+ <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
+
+ <application
+ android:label="Audio Service Demo"
+ android:name="${applicationName}"
+ android:icon="@mipmap/ic_launcher">
+ <activity
+ android:name="com.ryanheise.audioservice.AudioServiceActivity"
+ android:exported="true"
+ android:launchMode="singleTop"
+ android:theme="@style/LaunchTheme"
+ android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density"
+ android:hardwareAccelerated="true"
+ android:windowSoftInputMode="adjustResize"
+ tools:ignore="Instantiatable">
+ <!-- Specifies an Android theme to apply to this Activity as soon as
+ the Android process has started. This theme is visible to the user
+ while the Flutter UI initializes. After that, this theme continues
+ to determine the Window background behind the Flutter UI. -->
+ <meta-data
+ android:name="io.flutter.embedding.android.NormalTheme"
+ android:resource="@style/NormalTheme"
+ />
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN"/>
+ <category android:name="android.intent.category.LAUNCHER"/>
+ </intent-filter>
+ </activity>
+
+ <service
+ android:name="com.ryanheise.audioservice.AudioService"
+ android:foregroundServiceType="mediaPlayback"
+ android:exported="true"
+ tools:ignore="Instantiatable">
+ <intent-filter>
+ <action android:name="android.media.browse.MediaBrowserService" />
+ </intent-filter>
+ </service>
+
+ <receiver
+ android:name="com.ryanheise.audioservice.MediaButtonReceiver"
+ android:exported="true"
+ tools:ignore="Instantiatable">
+ <intent-filter>
+ <action android:name="android.intent.action.MEDIA_BUTTON" />
+ </intent-filter>
+ </receiver>
+
+ <meta-data
+ android:name="flutterEmbedding"
+ android:value="2" />
+
+ <meta-data
+ android:name="com.google.android.gms.car.application"
+ android:resource="@xml/automotive_app_desc" />
+
+ </application>
+</manifest>
diff --git a/packages/audio_service/example/android/app/src/main/java/com/ryanheise/audioserviceexample/MainActivity.java b/packages/audio_service/example/android/app/src/main/java/com/ryanheise/audioserviceexample/MainActivity.java
new file mode 100644
index 00000000..4a9c79d5
--- /dev/null
+++ b/packages/audio_service/example/android/app/src/main/java/com/ryanheise/audioserviceexample/MainActivity.java
@@ -0,0 +1,6 @@
+package com.ryanheise.audioserviceexample;
+
+import io.flutter.embedding.android.FlutterActivity;
+
+public class MainActivity extends FlutterActivity {
+}
diff --git a/packages/audio_service/example/android/app/src/main/res/drawable-hdpi/ic_action_pause.png b/packages/audio_service/example/android/app/src/main/res/drawable-hdpi/ic_action_pause.png
new file mode 100644
index 00000000..55f33b25
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/drawable-hdpi/ic_action_pause.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/drawable-hdpi/ic_action_play_arrow.png b/packages/audio_service/example/android/app/src/main/res/drawable-hdpi/ic_action_play_arrow.png
new file mode 100644
index 00000000..87d5743d
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/drawable-hdpi/ic_action_play_arrow.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/drawable-hdpi/ic_action_skip_next.png b/packages/audio_service/example/android/app/src/main/res/drawable-hdpi/ic_action_skip_next.png
new file mode 100644
index 00000000..28a76a3e
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/drawable-hdpi/ic_action_skip_next.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/drawable-hdpi/ic_action_skip_previous.png b/packages/audio_service/example/android/app/src/main/res/drawable-hdpi/ic_action_skip_previous.png
new file mode 100644
index 00000000..d60ff084
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/drawable-hdpi/ic_action_skip_previous.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/drawable-hdpi/ic_action_stop.png b/packages/audio_service/example/android/app/src/main/res/drawable-hdpi/ic_action_stop.png
new file mode 100644
index 00000000..5435114d
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/drawable-hdpi/ic_action_stop.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/drawable-mdpi/ic_action_pause.png b/packages/audio_service/example/android/app/src/main/res/drawable-mdpi/ic_action_pause.png
new file mode 100644
index 00000000..e8ff072d
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/drawable-mdpi/ic_action_pause.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/drawable-mdpi/ic_action_play_arrow.png b/packages/audio_service/example/android/app/src/main/res/drawable-mdpi/ic_action_play_arrow.png
new file mode 100644
index 00000000..71fff1d0
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/drawable-mdpi/ic_action_play_arrow.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/drawable-mdpi/ic_action_skip_next.png b/packages/audio_service/example/android/app/src/main/res/drawable-mdpi/ic_action_skip_next.png
new file mode 100644
index 00000000..632e4ab7
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/drawable-mdpi/ic_action_skip_next.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/drawable-mdpi/ic_action_skip_previous.png b/packages/audio_service/example/android/app/src/main/res/drawable-mdpi/ic_action_skip_previous.png
new file mode 100644
index 00000000..cf9b5f74
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/drawable-mdpi/ic_action_skip_previous.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/drawable-mdpi/ic_action_stop.png b/packages/audio_service/example/android/app/src/main/res/drawable-mdpi/ic_action_stop.png
new file mode 100644
index 00000000..95e837d9
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/drawable-mdpi/ic_action_stop.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/drawable-xhdpi/ic_action_pause.png b/packages/audio_service/example/android/app/src/main/res/drawable-xhdpi/ic_action_pause.png
new file mode 100644
index 00000000..fbdee835
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/drawable-xhdpi/ic_action_pause.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/drawable-xhdpi/ic_action_play_arrow.png b/packages/audio_service/example/android/app/src/main/res/drawable-xhdpi/ic_action_play_arrow.png
new file mode 100644
index 00000000..62d2067c
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/drawable-xhdpi/ic_action_play_arrow.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/drawable-xhdpi/ic_action_skip_next.png b/packages/audio_service/example/android/app/src/main/res/drawable-xhdpi/ic_action_skip_next.png
new file mode 100644
index 00000000..164718d7
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/drawable-xhdpi/ic_action_skip_next.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/drawable-xhdpi/ic_action_skip_previous.png b/packages/audio_service/example/android/app/src/main/res/drawable-xhdpi/ic_action_skip_previous.png
new file mode 100644
index 00000000..b33307ee
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/drawable-xhdpi/ic_action_skip_previous.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/drawable-xhdpi/ic_action_stop.png b/packages/audio_service/example/android/app/src/main/res/drawable-xhdpi/ic_action_stop.png
new file mode 100644
index 00000000..3f7f54d0
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/drawable-xhdpi/ic_action_stop.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/drawable-xxhdpi/ic_action_pause.png b/packages/audio_service/example/android/app/src/main/res/drawable-xxhdpi/ic_action_pause.png
new file mode 100644
index 00000000..8ac598d2
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/drawable-xxhdpi/ic_action_pause.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/drawable-xxhdpi/ic_action_play_arrow.png b/packages/audio_service/example/android/app/src/main/res/drawable-xxhdpi/ic_action_play_arrow.png
new file mode 100644
index 00000000..47ce73ad
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/drawable-xxhdpi/ic_action_play_arrow.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/drawable-xxhdpi/ic_action_skip_next.png b/packages/audio_service/example/android/app/src/main/res/drawable-xxhdpi/ic_action_skip_next.png
new file mode 100644
index 00000000..0f3b6a16
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/drawable-xxhdpi/ic_action_skip_next.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/drawable-xxhdpi/ic_action_skip_previous.png b/packages/audio_service/example/android/app/src/main/res/drawable-xxhdpi/ic_action_skip_previous.png
new file mode 100644
index 00000000..2e09dfa2
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/drawable-xxhdpi/ic_action_skip_previous.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/drawable-xxhdpi/ic_action_stop.png b/packages/audio_service/example/android/app/src/main/res/drawable-xxhdpi/ic_action_stop.png
new file mode 100644
index 00000000..17da4a36
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/drawable-xxhdpi/ic_action_stop.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/drawable-xxxhdpi/ic_action_pause.png b/packages/audio_service/example/android/app/src/main/res/drawable-xxxhdpi/ic_action_pause.png
new file mode 100644
index 00000000..43435028
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/drawable-xxxhdpi/ic_action_pause.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/drawable-xxxhdpi/ic_action_play_arrow.png b/packages/audio_service/example/android/app/src/main/res/drawable-xxxhdpi/ic_action_play_arrow.png
new file mode 100644
index 00000000..e9f92814
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/drawable-xxxhdpi/ic_action_play_arrow.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/drawable-xxxhdpi/ic_action_skip_next.png b/packages/audio_service/example/android/app/src/main/res/drawable-xxxhdpi/ic_action_skip_next.png
new file mode 100644
index 00000000..ea1a197c
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/drawable-xxxhdpi/ic_action_skip_next.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/drawable-xxxhdpi/ic_action_skip_previous.png b/packages/audio_service/example/android/app/src/main/res/drawable-xxxhdpi/ic_action_skip_previous.png
new file mode 100644
index 00000000..3dcbcd49
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/drawable-xxxhdpi/ic_action_skip_previous.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/drawable-xxxhdpi/ic_action_stop.png b/packages/audio_service/example/android/app/src/main/res/drawable-xxxhdpi/ic_action_stop.png
new file mode 100644
index 00000000..20ee1b7b
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/drawable-xxxhdpi/ic_action_stop.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/drawable/baseline_forward_30_24.xml b/packages/audio_service/example/android/app/src/main/res/drawable/baseline_forward_30_24.xml
new file mode 100644
index 00000000..f2f3216b
--- /dev/null
+++ b/packages/audio_service/example/android/app/src/main/res/drawable/baseline_forward_30_24.xml
@@ -0,0 +1,7 @@
+<vector android:height="24dp" android:tint="#000000"
+ android:viewportHeight="24" android:viewportWidth="24"
+ android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
+ <path android:fillColor="@android:color/white" android:pathData="M18,13c0,3.31 -2.69,6 -6,6s-6,-2.69 -6,-6s2.69,-6 6,-6v4l5,-5l-5,-5v4c-4.42,0 -8,3.58 -8,8c0,4.42 3.58,8 8,8s8,-3.58 8,-8H18z"/>
+ <path android:fillColor="@android:color/white" android:pathData="M10.06,15.38c-0.29,0 -0.62,-0.17 -0.62,-0.54H8.59c0,0.97 0.9,1.23 1.45,1.23c0.87,0 1.51,-0.46 1.51,-1.25c0,-0.66 -0.45,-0.9 -0.71,-1c0.11,-0.05 0.65,-0.32 0.65,-0.92c0,-0.21 -0.05,-1.22 -1.44,-1.22c-0.62,0 -1.4,0.35 -1.4,1.16h0.85c0,-0.34 0.31,-0.48 0.57,-0.48c0.59,0 0.58,0.5 0.58,0.54c0,0.52 -0.41,0.59 -0.63,0.59H9.56v0.66h0.45c0.65,0 0.7,0.42 0.7,0.64C10.71,15.11 10.5,15.38 10.06,15.38z"/>
+ <path android:fillColor="@android:color/white" android:pathData="M13.85,11.68c-0.14,0 -1.44,-0.08 -1.44,1.82v0.74c0,1.9 1.31,1.82 1.44,1.82c0.14,0 1.44,0.09 1.44,-1.82V13.5C15.3,11.59 13.99,11.68 13.85,11.68zM14.45,14.35c0,0.77 -0.21,1.03 -0.59,1.03c-0.38,0 -0.6,-0.26 -0.6,-1.03v-0.97c0,-0.75 0.22,-1.01 0.59,-1.01c0.38,0 0.6,0.26 0.6,1.01V14.35z"/>
+</vector>
diff --git a/packages/audio_service/example/android/app/src/main/res/drawable/ic_baseline_favorite_24.xml b/packages/audio_service/example/android/app/src/main/res/drawable/ic_baseline_favorite_24.xml
new file mode 100644
index 00000000..52d28592
--- /dev/null
+++ b/packages/audio_service/example/android/app/src/main/res/drawable/ic_baseline_favorite_24.xml
@@ -0,0 +1,5 @@
+<vector android:height="24dp" android:tint="#000000"
+ android:viewportHeight="24" android:viewportWidth="24"
+ android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
+ <path android:fillColor="@android:color/white" android:pathData="M12,21.35l-1.45,-1.32C5.4,15.36 2,12.28 2,8.5 2,5.42 4.42,3 7.5,3c1.74,0 3.41,0.81 4.5,2.09C13.09,3.81 14.76,3 16.5,3 19.58,3 22,5.42 22,8.5c0,3.78 -3.4,6.86 -8.55,11.54L12,21.35z"/>
+</vector>
diff --git a/packages/audio_service/example/android/app/src/main/res/drawable/launch_background.xml b/packages/audio_service/example/android/app/src/main/res/drawable/launch_background.xml
new file mode 100644
index 00000000..304732f8
--- /dev/null
+++ b/packages/audio_service/example/android/app/src/main/res/drawable/launch_background.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Modify this file to customize your launch splash screen -->
+<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
+ <item android:drawable="@android:color/white" />
+
+ <!-- You can insert your own image assets here -->
+ <!-- <item>
+ <bitmap
+ android:gravity="center"
+ android:src="@mipmap/launch_image" />
+ </item> -->
+</layer-list>
diff --git a/packages/audio_service/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/packages/audio_service/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png
new file mode 100644
index 00000000..db77bb4b
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/packages/audio_service/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png
new file mode 100644
index 00000000..17987b79
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/packages/audio_service/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png
new file mode 100644
index 00000000..09d43914
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/packages/audio_service/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
new file mode 100644
index 00000000..d5f1c8d3
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/packages/audio_service/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
new file mode 100644
index 00000000..4d6372ee
Binary files /dev/null and b/packages/audio_service/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ
diff --git a/packages/audio_service/example/android/app/src/main/res/raw/keep.xml b/packages/audio_service/example/android/app/src/main/res/raw/keep.xml
new file mode 100644
index 00000000..4883485b
--- /dev/null
+++ b/packages/audio_service/example/android/app/src/main/res/raw/keep.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources xmlns:tools="http://schemas.android.com/tools"
+ tools:keep="@drawable/*" />
+
+<!-- This forces R8 to keep all drawables from being stripped away in release builds -->
diff --git a/packages/audio_service/example/android/app/src/main/res/values/styles.xml b/packages/audio_service/example/android/app/src/main/res/values/styles.xml
new file mode 100644
index 00000000..cb1ef880
--- /dev/null
+++ b/packages/audio_service/example/android/app/src/main/res/values/styles.xml
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->
+ <style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">
+ <!-- Show a splash screen on the activity. Automatically removed when
+ the Flutter engine draws its first frame -->
+ <item name="android:windowBackground">@drawable/launch_background</item>
+ </style>
+ <!-- Theme applied to the Android Window as soon as the process has started.
+ This theme determines the color of the Android Window while your
+ Flutter UI initializes, as well as behind your Flutter UI while its
+ running.
+
+ This Theme is only used starting with V2 of Flutter's Android embedding. -->
+ <style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
+ <item name="android:windowBackground">?android:colorBackground</item>
+ </style>
+</resources>
diff --git a/packages/audio_service/example/android/app/src/main/res/xml/automotive_app_desc.xml b/packages/audio_service/example/android/app/src/main/res/xml/automotive_app_desc.xml
new file mode 100644
index 00000000..e2db349d
--- /dev/null
+++ b/packages/audio_service/example/android/app/src/main/res/xml/automotive_app_desc.xml
@@ -0,0 +1,3 @@
+<automotiveApp>
+ <uses name="media"/>
+</automotiveApp>
diff --git a/packages/audio_service/example/android/build.gradle b/packages/audio_service/example/android/build.gradle
new file mode 100644
index 00000000..33a95e7b
--- /dev/null
+++ b/packages/audio_service/example/android/build.gradle
@@ -0,0 +1,26 @@
+allprojects {
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+
+rootProject.buildDir = "../build"
+subprojects {
+ project.buildDir = "${rootProject.buildDir}/${project.name}"
+}
+subprojects {
+ project.evaluationDependsOn(":app")
+}
+
+tasks.register("clean", Delete) {
+ delete rootProject.buildDir
+}
+
+gradle.projectsEvaluated {
+ project(":audio_service") {
+ tasks.withType(JavaCompile) {
+ options.compilerArgs << "-Werror"
+ }
+ }
+}
diff --git a/packages/audio_service/example/android/gradle.properties b/packages/audio_service/example/android/gradle.properties
new file mode 100644
index 00000000..c9656581
--- /dev/null
+++ b/packages/audio_service/example/android/gradle.properties
@@ -0,0 +1,7 @@
+org.gradle.jvmargs=-Xmx1536M
+android.enableJetifier=true
+android.useAndroidX=true
+android.enableR8=true
+android.defaults.buildfeatures.buildconfig=true
+android.nonTransitiveRClass=false
+android.nonFinalResIds=false
diff --git a/packages/audio_service/example/android/gradle/wrapper/gradle-wrapper.properties b/packages/audio_service/example/android/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 00000000..e01db0fe
--- /dev/null
+++ b/packages/audio_service/example/android/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+#Sat Mar 22 15:01:44 AEDT 2025
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/packages/audio_service/example/android/settings.gradle b/packages/audio_service/example/android/settings.gradle
new file mode 100644
index 00000000..c5ab4b5c
--- /dev/null
+++ b/packages/audio_service/example/android/settings.gradle
@@ -0,0 +1,25 @@
+pluginManagement {
+ def flutterSdkPath = {
+ def properties = new Properties()
+ file("local.properties").withInputStream { properties.load(it) }
+ def flutterSdkPath = properties.getProperty("flutter.sdk")
+ assert flutterSdkPath != null, "flutter.sdk not set in local.properties"
+ return flutterSdkPath
+ }()
+
+ includeBuild("$flutterSdkPath/packages/flutter_tools/gradle")
+
+ repositories {
+ google()
+ mavenCentral()
+ gradlePluginPortal()
+ }
+}
+
+plugins {
+ id "dev.flutter.flutter-plugin-loader" version "1.0.0"
+ id "com.android.application" version "8.5.2" apply false
+ id "org.jetbrains.kotlin.android" version "1.8.22" apply false
+}
+
+include ":app"
diff --git a/packages/audio_service/example/android/settings_aar.gradle b/packages/audio_service/example/android/settings_aar.gradle
new file mode 100644
index 00000000..e7b4def4
--- /dev/null
+++ b/packages/audio_service/example/android/settings_aar.gradle
@@ -0,0 +1 @@
+include ':app'
diff --git a/packages/audio_service/example/ios/Flutter/AppFrameworkInfo.plist b/packages/audio_service/example/ios/Flutter/AppFrameworkInfo.plist
new file mode 100644
index 00000000..8c6e5614
--- /dev/null
+++ b/packages/audio_service/example/ios/Flutter/AppFrameworkInfo.plist
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>$(DEVELOPMENT_LANGUAGE)</string>
+ <key>CFBundleExecutable</key>
+ <string>App</string>
+ <key>CFBundleIdentifier</key>
+ <string>io.flutter.flutter.app</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string>App</string>
+ <key>CFBundlePackageType</key>
+ <string>FMWK</string>
+ <key>CFBundleShortVersionString</key>
+ <string>1.0</string>
+ <key>CFBundleSignature</key>
+ <string>????</string>
+ <key>CFBundleVersion</key>
+ <string>1.0</string>
+ <key>MinimumOSVersion</key>
+ <string>12.0</string>
+</dict>
+</plist>
diff --git a/packages/audio_service/example/ios/Flutter/Debug.xcconfig b/packages/audio_service/example/ios/Flutter/Debug.xcconfig
new file mode 100644
index 00000000..e8efba11
--- /dev/null
+++ b/packages/audio_service/example/ios/Flutter/Debug.xcconfig
@@ -0,0 +1,2 @@
+#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"
+#include "Generated.xcconfig"
diff --git a/packages/audio_service/example/ios/Flutter/Release.xcconfig b/packages/audio_service/example/ios/Flutter/Release.xcconfig
new file mode 100644
index 00000000..399e9340
--- /dev/null
+++ b/packages/audio_service/example/ios/Flutter/Release.xcconfig
@@ -0,0 +1,2 @@
+#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"
+#include "Generated.xcconfig"
diff --git a/packages/audio_service/example/ios/Podfile b/packages/audio_service/example/ios/Podfile
new file mode 100644
index 00000000..279576f3
--- /dev/null
+++ b/packages/audio_service/example/ios/Podfile
@@ -0,0 +1,41 @@
+# Uncomment this line to define a global platform for your project
+# platform :ios, '12.0'
+
+# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
+ENV['COCOAPODS_DISABLE_STATS'] = 'true'
+
+project 'Runner', {
+ 'Debug' => :debug,
+ 'Profile' => :release,
+ 'Release' => :release,
+}
+
+def flutter_root
+ generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
+ unless File.exist?(generated_xcode_build_settings_path)
+ raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
+ end
+
+ File.foreach(generated_xcode_build_settings_path) do |line|
+ matches = line.match(/FLUTTER_ROOT\=(.*)/)
+ return matches[1].strip if matches
+ end
+ raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
+end
+
+require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)
+
+flutter_ios_podfile_setup
+
+target 'Runner' do
+ use_frameworks!
+ use_modular_headers!
+
+ flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
+end
+
+post_install do |installer|
+ installer.pods_project.targets.each do |target|
+ flutter_additional_ios_build_settings(target)
+ end
+end
diff --git a/packages/audio_service/example/ios/Podfile.lock b/packages/audio_service/example/ios/Podfile.lock
new file mode 100644
index 00000000..472b8fde
--- /dev/null
+++ b/packages/audio_service/example/ios/Podfile.lock
@@ -0,0 +1,55 @@
+PODS:
+ - device_info_plus (0.0.1):
+ - Flutter
+ - Flutter (1.0.0)
+ - flutter_tts (0.0.1):
+ - Flutter
+ - FMDB (2.7.5):
+ - FMDB/standard (= 2.7.5)
+ - FMDB/standard (2.7.5)
+ - path_provider_ios (0.0.1):
+ - Flutter
+ - permission_handler_apple (9.3.0):
+ - Flutter
+ - sqflite (0.0.2):
+ - Flutter
+ - FMDB (>= 2.7.5)
+
+DEPENDENCIES:
+ - device_info_plus (from `.symlinks/plugins/device_info_plus/ios`)
+ - Flutter (from `Flutter`)
+ - flutter_tts (from `.symlinks/plugins/flutter_tts/ios`)
+ - path_provider_ios (from `.symlinks/plugins/path_provider_ios/ios`)
+ - permission_handler_apple (from `.symlinks/plugins/permission_handler_apple/ios`)
+ - sqflite (from `.symlinks/plugins/sqflite/ios`)
+
+SPEC REPOS:
+ trunk:
+ - FMDB
+
+EXTERNAL SOURCES:
+ device_info_plus:
+ :path: ".symlinks/plugins/device_info_plus/ios"
+ Flutter:
+ :path: Flutter
+ flutter_tts:
+ :path: ".symlinks/plugins/flutter_tts/ios"
+ path_provider_ios:
+ :path: ".symlinks/plugins/path_provider_ios/ios"
+ permission_handler_apple:
+ :path: ".symlinks/plugins/permission_handler_apple/ios"
+ sqflite:
+ :path: ".symlinks/plugins/sqflite/ios"
+
+SPEC CHECKSUMS:
+ device_info_plus: c6fb39579d0f423935b0c9ce7ee2f44b71b9fce6
+ Flutter: e0871f40cf51350855a761d2e70bf5af5b9b5de7
+ flutter_tts: 0f492aab6accf87059b72354fcb4ba934304771d
+ FMDB: 2ce00b547f966261cd18927a3ddb07cb6f3db82a
+ path_provider_ios: 7d7ce634493af4477d156294792024ec3485acd5
+ permission_handler_apple: 9878588469a2b0d0fc1e048d9f43605f92e6cec2
+ sqflite: 6d358c025f5b867b29ed92fc697fd34924e11904
+
+PODFILE CHECKSUM: c4c93c5f6502fe2754f48404d3594bf779584011
+
+COCOAPODS: 1.15.2
diff --git a/packages/audio_service/example/ios/Runner.xcodeproj/project.pbxproj b/packages/audio_service/example/ios/Runner.xcodeproj/project.pbxproj
new file mode 100644
index 00000000..95e6c998
--- /dev/null
+++ b/packages/audio_service/example/ios/Runner.xcodeproj/project.pbxproj
@@ -0,0 +1,630 @@
+// !$*UTF8*$!
+{
+ archiveVersion = 1;
+ classes = {
+ };
+ objectVersion = 54;
+ objects = {
+
+/* Begin PBXBuildFile section */
+ 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; };
+ 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; };
+ 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; };
+ 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; };
+ 9740EEB41CF90195004384FC /* Debug.xcconfig in Resources */ = {isa = PBXBuildFile; fileRef = 9740EEB21CF90195004384FC /* Debug.xcconfig */; };
+ 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };
+ 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; };
+ 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; };
+ AED074950218D357B0D72E2F /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 40823A0F86E5AFAAAC194463 /* Pods_Runner.framework */; };
+/* End PBXBuildFile section */
+
+/* Begin PBXCopyFilesBuildPhase section */
+ 9705A1C41CF9048500538489 /* Embed Frameworks */ = {
+ isa = PBXCopyFilesBuildPhase;
+ buildActionMask = 2147483647;
+ dstPath = "";
+ dstSubfolderSpec = 10;
+ files = (
+ );
+ name = "Embed Frameworks";
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+/* End PBXCopyFilesBuildPhase section */
+
+/* Begin PBXFileReference section */
+ 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = "<group>"; };
+ 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = "<group>"; };
+ 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = "<group>"; };
+ 40823A0F86E5AFAAAC194463 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; };
+ 543859E2B3E3CA5C92A65955 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = "<group>"; };
+ 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = "<group>"; };
+ 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
+ 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = "<group>"; };
+ 8FA30B821688EEAE2CA8A761 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = "<group>"; };
+ 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = "<group>"; };
+ 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = "<group>"; };
+ 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; };
+ 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
+ 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
+ 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
+ 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
+ BA340997E38F083F433361DA /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = "<group>"; };
+/* End PBXFileReference section */
+
+/* Begin PBXFrameworksBuildPhase section */
+ 97C146EB1CF9000F007C117D /* Frameworks */ = {
+ isa = PBXFrameworksBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */,
+ AED074950218D357B0D72E2F /* Pods_Runner.framework in Frameworks */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+/* End PBXFrameworksBuildPhase section */
+
+/* Begin PBXGroup section */
+ 5EB1FF49C2022CF25CD11CE5 /* Frameworks */ = {
+ isa = PBXGroup;
+ children = (
+ 40823A0F86E5AFAAAC194463 /* Pods_Runner.framework */,
+ );
+ name = Frameworks;
+ sourceTree = "<group>";
+ };
+ 9740EEB11CF90186004384FC /* Flutter */ = {
+ isa = PBXGroup;
+ children = (
+ 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */,
+ 9740EEB21CF90195004384FC /* Debug.xcconfig */,
+ 7AFA3C8E1D35360C0083082E /* Release.xcconfig */,
+ 9740EEB31CF90195004384FC /* Generated.xcconfig */,
+ );
+ name = Flutter;
+ sourceTree = "<group>";
+ };
+ 97C146E51CF9000F007C117D = {
+ isa = PBXGroup;
+ children = (
+ 9740EEB11CF90186004384FC /* Flutter */,
+ 97C146F01CF9000F007C117D /* Runner */,
+ 97C146EF1CF9000F007C117D /* Products */,
+ D43FF3E498A859D612533C0C /* Pods */,
+ 5EB1FF49C2022CF25CD11CE5 /* Frameworks */,
+ );
+ sourceTree = "<group>";
+ };
+ 97C146EF1CF9000F007C117D /* Products */ = {
+ isa = PBXGroup;
+ children = (
+ 97C146EE1CF9000F007C117D /* Runner.app */,
+ );
+ name = Products;
+ sourceTree = "<group>";
+ };
+ 97C146F01CF9000F007C117D /* Runner */ = {
+ isa = PBXGroup;
+ children = (
+ 97C146FA1CF9000F007C117D /* Main.storyboard */,
+ 97C146FD1CF9000F007C117D /* Assets.xcassets */,
+ 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */,
+ 97C147021CF9000F007C117D /* Info.plist */,
+ 97C146F11CF9000F007C117D /* Supporting Files */,
+ 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */,
+ 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */,
+ 74858FAE1ED2DC5600515810 /* AppDelegate.swift */,
+ 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */,
+ );
+ path = Runner;
+ sourceTree = "<group>";
+ };
+ 97C146F11CF9000F007C117D /* Supporting Files */ = {
+ isa = PBXGroup;
+ children = (
+ );
+ name = "Supporting Files";
+ sourceTree = "<group>";
+ };
+ D43FF3E498A859D612533C0C /* Pods */ = {
+ isa = PBXGroup;
+ children = (
+ BA340997E38F083F433361DA /* Pods-Runner.debug.xcconfig */,
+ 543859E2B3E3CA5C92A65955 /* Pods-Runner.release.xcconfig */,
+ 8FA30B821688EEAE2CA8A761 /* Pods-Runner.profile.xcconfig */,
+ );
+ path = Pods;
+ sourceTree = "<group>";
+ };
+/* End PBXGroup section */
+
+/* Begin PBXNativeTarget section */
+ 97C146ED1CF9000F007C117D /* Runner */ = {
+ isa = PBXNativeTarget;
+ buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */;
+ buildPhases = (
+ B3D25085827780F927C3917A /* [CP] Check Pods Manifest.lock */,
+ 9740EEB61CF901F6004384FC /* Run Script */,
+ 97C146EA1CF9000F007C117D /* Sources */,
+ 97C146EB1CF9000F007C117D /* Frameworks */,
+ 97C146EC1CF9000F007C117D /* Resources */,
+ 9705A1C41CF9048500538489 /* Embed Frameworks */,
+ 3B06AD1E1E4923F5004D2608 /* Thin Binary */,
+ 9DA173EC5076B905CFA88B40 /* [CP] Embed Pods Frameworks */,
+ E34CCBF45F755EBF9FB78E37 /* [CP] Copy Pods Resources */,
+ );
+ buildRules = (
+ );
+ dependencies = (
+ );
+ name = Runner;
+ packageProductDependencies = (
+ 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */,
+ );
+ productName = Runner;
+ productReference = 97C146EE1CF9000F007C117D /* Runner.app */;
+ productType = "com.apple.product-type.application";
+ };
+/* End PBXNativeTarget section */
+
+/* Begin PBXProject section */
+ 97C146E61CF9000F007C117D /* Project object */ = {
+ isa = PBXProject;
+ attributes = {
+ LastUpgradeCheck = 1510;
+ ORGANIZATIONNAME = "The Chromium Authors";
+ TargetAttributes = {
+ 97C146ED1CF9000F007C117D = {
+ CreatedOnToolsVersion = 7.3.1;
+ LastSwiftMigration = 0910;
+ };
+ };
+ };
+ buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */;
+ compatibilityVersion = "Xcode 3.2";
+ developmentRegion = en;
+ hasScannedForEncodings = 0;
+ knownRegions = (
+ en,
+ Base,
+ );
+ mainGroup = 97C146E51CF9000F007C117D;
+ packageReferences = (
+ 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "FlutterGeneratedPluginSwiftPackage" */,
+ );
+ productRefGroup = 97C146EF1CF9000F007C117D /* Products */;
+ projectDirPath = "";
+ projectRoot = "";
+ targets = (
+ 97C146ED1CF9000F007C117D /* Runner */,
+ );
+ };
+/* End PBXProject section */
+
+/* Begin PBXResourcesBuildPhase section */
+ 97C146EC1CF9000F007C117D /* Resources */ = {
+ isa = PBXResourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */,
+ 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */,
+ 9740EEB41CF90195004384FC /* Debug.xcconfig in Resources */,
+ 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */,
+ 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+/* End PBXResourcesBuildPhase section */
+
+/* Begin PBXShellScriptBuildPhase section */
+ 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = {
+ isa = PBXShellScriptBuildPhase;
+ alwaysOutOfDate = 1;
+ buildActionMask = 2147483647;
+ files = (
+ );
+ inputPaths = (
+ "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}",
+ );
+ name = "Thin Binary";
+ outputPaths = (
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ shellPath = /bin/sh;
+ shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin";
+ };
+ 9740EEB61CF901F6004384FC /* Run Script */ = {
+ isa = PBXShellScriptBuildPhase;
+ alwaysOutOfDate = 1;
+ buildActionMask = 2147483647;
+ files = (
+ );
+ inputPaths = (
+ );
+ name = "Run Script";
+ outputPaths = (
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ shellPath = /bin/sh;
+ shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build";
+ };
+ 9DA173EC5076B905CFA88B40 /* [CP] Embed Pods Frameworks */ = {
+ isa = PBXShellScriptBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ );
+ inputPaths = (
+ "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh",
+ "${BUILT_PRODUCTS_DIR}/FMDB/FMDB.framework",
+ "${BUILT_PRODUCTS_DIR}/device_info_plus/device_info_plus.framework",
+ "${BUILT_PRODUCTS_DIR}/path_provider_ios/path_provider_ios.framework",
+ "${BUILT_PRODUCTS_DIR}/sqflite/sqflite.framework",
+ );
+ name = "[CP] Embed Pods Frameworks";
+ outputPaths = (
+ "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/FMDB.framework",
+ "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/device_info_plus.framework",
+ "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/path_provider_ios.framework",
+ "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/sqflite.framework",
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ shellPath = /bin/sh;
+ shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n";
+ showEnvVarsInLog = 0;
+ };
+ B3D25085827780F927C3917A /* [CP] Check Pods Manifest.lock */ = {
+ isa = PBXShellScriptBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ );
+ inputFileListPaths = (
+ );
+ inputPaths = (
+ "${PODS_PODFILE_DIR_PATH}/Podfile.lock",
+ "${PODS_ROOT}/Manifest.lock",
+ );
+ name = "[CP] Check Pods Manifest.lock";
+ outputFileListPaths = (
+ );
+ outputPaths = (
+ "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt",
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ shellPath = /bin/sh;
+ shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
+ showEnvVarsInLog = 0;
+ };
+ E34CCBF45F755EBF9FB78E37 /* [CP] Copy Pods Resources */ = {
+ isa = PBXShellScriptBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ );
+ inputPaths = (
+ "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources.sh",
+ "${PODS_CONFIGURATION_BUILD_DIR}/permission_handler_apple/permission_handler_apple_privacy.bundle",
+ );
+ name = "[CP] Copy Pods Resources";
+ outputPaths = (
+ "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/permission_handler_apple_privacy.bundle",
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ shellPath = /bin/sh;
+ shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources.sh\"\n";
+ showEnvVarsInLog = 0;
+ };
+/* End PBXShellScriptBuildPhase section */
+
+/* Begin PBXSourcesBuildPhase section */
+ 97C146EA1CF9000F007C117D /* Sources */ = {
+ isa = PBXSourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */,
+ 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+/* End PBXSourcesBuildPhase section */
+
+/* Begin PBXVariantGroup section */
+ 97C146FA1CF9000F007C117D /* Main.storyboard */ = {
+ isa = PBXVariantGroup;
+ children = (
+ 97C146FB1CF9000F007C117D /* Base */,
+ );
+ name = Main.storyboard;
+ sourceTree = "<group>";
+ };
+ 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = {
+ isa = PBXVariantGroup;
+ children = (
+ 97C147001CF9000F007C117D /* Base */,
+ );
+ name = LaunchScreen.storyboard;
+ sourceTree = "<group>";
+ };
+/* End PBXVariantGroup section */
+
+/* Begin XCBuildConfiguration section */
+ 249021D3217E4FDB00AE95B9 /* Profile */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ALWAYS_SEARCH_USER_PATHS = NO;
+ CLANG_ANALYZER_NONNULL = YES;
+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
+ CLANG_CXX_LIBRARY = "libc++";
+ CLANG_ENABLE_MODULES = YES;
+ CLANG_ENABLE_OBJC_ARC = YES;
+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
+ CLANG_WARN_BOOL_CONVERSION = YES;
+ CLANG_WARN_COMMA = YES;
+ CLANG_WARN_CONSTANT_CONVERSION = YES;
+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
+ CLANG_WARN_EMPTY_BODY = YES;
+ CLANG_WARN_ENUM_CONVERSION = YES;
+ CLANG_WARN_INFINITE_RECURSION = YES;
+ CLANG_WARN_INT_CONVERSION = YES;
+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
+ CLANG_WARN_STRICT_PROTOTYPES = YES;
+ CLANG_WARN_SUSPICIOUS_MOVE = YES;
+ CLANG_WARN_UNREACHABLE_CODE = YES;
+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
+ "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
+ COPY_PHASE_STRIP = NO;
+ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+ ENABLE_NS_ASSERTIONS = NO;
+ ENABLE_STRICT_OBJC_MSGSEND = YES;
+ GCC_C_LANGUAGE_STANDARD = gnu99;
+ GCC_NO_COMMON_BLOCKS = YES;
+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
+ GCC_WARN_UNDECLARED_SELECTOR = YES;
+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
+ GCC_WARN_UNUSED_FUNCTION = YES;
+ GCC_WARN_UNUSED_VARIABLE = YES;
+ IPHONEOS_DEPLOYMENT_TARGET = 12.0;
+ MTL_ENABLE_DEBUG_INFO = NO;
+ SDKROOT = iphoneos;
+ TARGETED_DEVICE_FAMILY = "1,2";
+ VALIDATE_PRODUCT = YES;
+ };
+ name = Profile;
+ };
+ 249021D4217E4FDB00AE95B9 /* Profile */ = {
+ isa = XCBuildConfiguration;
+ baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
+ buildSettings = {
+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+ CLANG_ENABLE_MODULES = YES;
+ CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
+ ENABLE_BITCODE = NO;
+ FRAMEWORK_SEARCH_PATHS = (
+ "$(inherited)",
+ "$(PROJECT_DIR)/Flutter",
+ );
+ INFOPLIST_FILE = Runner/Info.plist;
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@executable_path/Frameworks",
+ );
+ LIBRARY_SEARCH_PATHS = (
+ "$(inherited)",
+ "$(PROJECT_DIR)/Flutter",
+ );
+ PRODUCT_BUNDLE_IDENTIFIER = com.ryanheise.audioServiceExample;
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
+ SWIFT_VERSION = 4.0;
+ VERSIONING_SYSTEM = "apple-generic";
+ };
+ name = Profile;
+ };
+ 97C147031CF9000F007C117D /* Debug */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ALWAYS_SEARCH_USER_PATHS = NO;
+ CLANG_ANALYZER_NONNULL = YES;
+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
+ CLANG_CXX_LIBRARY = "libc++";
+ CLANG_ENABLE_MODULES = YES;
+ CLANG_ENABLE_OBJC_ARC = YES;
+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
+ CLANG_WARN_BOOL_CONVERSION = YES;
+ CLANG_WARN_COMMA = YES;
+ CLANG_WARN_CONSTANT_CONVERSION = YES;
+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
+ CLANG_WARN_EMPTY_BODY = YES;
+ CLANG_WARN_ENUM_CONVERSION = YES;
+ CLANG_WARN_INFINITE_RECURSION = YES;
+ CLANG_WARN_INT_CONVERSION = YES;
+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
+ CLANG_WARN_STRICT_PROTOTYPES = YES;
+ CLANG_WARN_SUSPICIOUS_MOVE = YES;
+ CLANG_WARN_UNREACHABLE_CODE = YES;
+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
+ "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
+ COPY_PHASE_STRIP = NO;
+ DEBUG_INFORMATION_FORMAT = dwarf;
+ ENABLE_STRICT_OBJC_MSGSEND = YES;
+ ENABLE_TESTABILITY = YES;
+ GCC_C_LANGUAGE_STANDARD = gnu99;
+ GCC_DYNAMIC_NO_PIC = NO;
+ GCC_NO_COMMON_BLOCKS = YES;
+ GCC_OPTIMIZATION_LEVEL = 0;
+ GCC_PREPROCESSOR_DEFINITIONS = (
+ "DEBUG=1",
+ "$(inherited)",
+ );
+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
+ GCC_WARN_UNDECLARED_SELECTOR = YES;
+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
+ GCC_WARN_UNUSED_FUNCTION = YES;
+ GCC_WARN_UNUSED_VARIABLE = YES;
+ IPHONEOS_DEPLOYMENT_TARGET = 12.0;
+ MTL_ENABLE_DEBUG_INFO = YES;
+ ONLY_ACTIVE_ARCH = YES;
+ SDKROOT = iphoneos;
+ TARGETED_DEVICE_FAMILY = "1,2";
+ };
+ name = Debug;
+ };
+ 97C147041CF9000F007C117D /* Release */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ALWAYS_SEARCH_USER_PATHS = NO;
+ CLANG_ANALYZER_NONNULL = YES;
+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
+ CLANG_CXX_LIBRARY = "libc++";
+ CLANG_ENABLE_MODULES = YES;
+ CLANG_ENABLE_OBJC_ARC = YES;
+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
+ CLANG_WARN_BOOL_CONVERSION = YES;
+ CLANG_WARN_COMMA = YES;
+ CLANG_WARN_CONSTANT_CONVERSION = YES;
+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
+ CLANG_WARN_EMPTY_BODY = YES;
+ CLANG_WARN_ENUM_CONVERSION = YES;
+ CLANG_WARN_INFINITE_RECURSION = YES;
+ CLANG_WARN_INT_CONVERSION = YES;
+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
+ CLANG_WARN_STRICT_PROTOTYPES = YES;
+ CLANG_WARN_SUSPICIOUS_MOVE = YES;
+ CLANG_WARN_UNREACHABLE_CODE = YES;
+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
+ "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
+ COPY_PHASE_STRIP = NO;
+ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+ ENABLE_NS_ASSERTIONS = NO;
+ ENABLE_STRICT_OBJC_MSGSEND = YES;
+ GCC_C_LANGUAGE_STANDARD = gnu99;
+ GCC_NO_COMMON_BLOCKS = YES;
+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
+ GCC_WARN_UNDECLARED_SELECTOR = YES;
+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
+ GCC_WARN_UNUSED_FUNCTION = YES;
+ GCC_WARN_UNUSED_VARIABLE = YES;
+ IPHONEOS_DEPLOYMENT_TARGET = 12.0;
+ MTL_ENABLE_DEBUG_INFO = NO;
+ SDKROOT = iphoneos;
+ SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
+ TARGETED_DEVICE_FAMILY = "1,2";
+ VALIDATE_PRODUCT = YES;
+ };
+ name = Release;
+ };
+ 97C147061CF9000F007C117D /* Debug */ = {
+ isa = XCBuildConfiguration;
+ baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */;
+ buildSettings = {
+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+ CLANG_ENABLE_MODULES = YES;
+ CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
+ ENABLE_BITCODE = NO;
+ FRAMEWORK_SEARCH_PATHS = (
+ "$(inherited)",
+ "$(PROJECT_DIR)/Flutter",
+ );
+ INFOPLIST_FILE = Runner/Info.plist;
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@executable_path/Frameworks",
+ );
+ LIBRARY_SEARCH_PATHS = (
+ "$(inherited)",
+ "$(PROJECT_DIR)/Flutter",
+ );
+ PRODUCT_BUNDLE_IDENTIFIER = com.ryanheise.audioServiceExample;
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
+ SWIFT_OPTIMIZATION_LEVEL = "-Onone";
+ SWIFT_VERSION = 4.0;
+ VERSIONING_SYSTEM = "apple-generic";
+ };
+ name = Debug;
+ };
+ 97C147071CF9000F007C117D /* Release */ = {
+ isa = XCBuildConfiguration;
+ baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
+ buildSettings = {
+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+ CLANG_ENABLE_MODULES = YES;
+ CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
+ ENABLE_BITCODE = NO;
+ FRAMEWORK_SEARCH_PATHS = (
+ "$(inherited)",
+ "$(PROJECT_DIR)/Flutter",
+ );
+ INFOPLIST_FILE = Runner/Info.plist;
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@executable_path/Frameworks",
+ );
+ LIBRARY_SEARCH_PATHS = (
+ "$(inherited)",
+ "$(PROJECT_DIR)/Flutter",
+ );
+ PRODUCT_BUNDLE_IDENTIFIER = com.ryanheise.audioServiceExample;
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
+ SWIFT_VERSION = 4.0;
+ VERSIONING_SYSTEM = "apple-generic";
+ };
+ name = Release;
+ };
+/* End XCBuildConfiguration section */
+
+/* Begin XCConfigurationList section */
+ 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ 97C147031CF9000F007C117D /* Debug */,
+ 97C147041CF9000F007C117D /* Release */,
+ 249021D3217E4FDB00AE95B9 /* Profile */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Release;
+ };
+ 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ 97C147061CF9000F007C117D /* Debug */,
+ 97C147071CF9000F007C117D /* Release */,
+ 249021D4217E4FDB00AE95B9 /* Profile */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Release;
+ };
+/* End XCConfigurationList section */
+
+/* Begin XCLocalSwiftPackageReference section */
+ 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "FlutterGeneratedPluginSwiftPackage" */ = {
+ isa = XCLocalSwiftPackageReference;
+ relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage;
+ };
+/* End XCLocalSwiftPackageReference section */
+
+/* Begin XCSwiftPackageProductDependency section */
+ 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = {
+ isa = XCSwiftPackageProductDependency;
+ productName = FlutterGeneratedPluginSwiftPackage;
+ };
+/* End XCSwiftPackageProductDependency section */
+ };
+ rootObject = 97C146E61CF9000F007C117D /* Project object */;
+}
diff --git a/packages/audio_service/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/packages/audio_service/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata
new file mode 100644
index 00000000..919434a6
--- /dev/null
+++ b/packages/audio_service/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Workspace
+ version = "1.0">
+ <FileRef
+ location = "self:">
+ </FileRef>
+</Workspace>
diff --git a/packages/audio_service/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/packages/audio_service/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
new file mode 100644
index 00000000..18d98100
--- /dev/null
+++ b/packages/audio_service/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>IDEDidComputeMac32BitWarning</key>
+ <true/>
+</dict>
+</plist>
diff --git a/packages/audio_service/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/packages/audio_service/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings
new file mode 100644
index 00000000..f9b0d7c5
--- /dev/null
+++ b/packages/audio_service/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>PreviewsEnabled</key>
+ <false/>
+</dict>
+</plist>
diff --git a/packages/audio_service/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/packages/audio_service/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme
new file mode 100644
index 00000000..e598ba79
--- /dev/null
+++ b/packages/audio_service/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme
@@ -0,0 +1,105 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Scheme
+ LastUpgradeVersion = "1510"
+ version = "1.3">
+ <BuildAction
+ parallelizeBuildables = "YES"
+ buildImplicitDependencies = "YES">
+ <PreActions>
+ <ExecutionAction
+ ActionType = "Xcode.IDEStandardExecutionActionsCore.ExecutionActionType.ShellScriptAction">
+ <ActionContent
+ title = "Run Prepare Flutter Framework Script"
+ scriptText = "/bin/sh &quot;$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh&quot; prepare&#10;">
+ <EnvironmentBuildable>
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "97C146ED1CF9000F007C117D"
+ BuildableName = "Runner.app"
+ BlueprintName = "Runner"
+ ReferencedContainer = "container:Runner.xcodeproj">
+ </BuildableReference>
+ </EnvironmentBuildable>
+ </ActionContent>
+ </ExecutionAction>
+ </PreActions>
+ <BuildActionEntries>
+ <BuildActionEntry
+ buildForTesting = "YES"
+ buildForRunning = "YES"
+ buildForProfiling = "YES"
+ buildForArchiving = "YES"
+ buildForAnalyzing = "YES">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "97C146ED1CF9000F007C117D"
+ BuildableName = "Runner.app"
+ BlueprintName = "Runner"
+ ReferencedContainer = "container:Runner.xcodeproj">
+ </BuildableReference>
+ </BuildActionEntry>
+ </BuildActionEntries>
+ </BuildAction>
+ <TestAction
+ buildConfiguration = "Debug"
+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+ shouldUseLaunchSchemeArgsEnv = "YES">
+ <MacroExpansion>
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "97C146ED1CF9000F007C117D"
+ BuildableName = "Runner.app"
+ BlueprintName = "Runner"
+ ReferencedContainer = "container:Runner.xcodeproj">
+ </BuildableReference>
+ </MacroExpansion>
+ <Testables>
+ </Testables>
+ </TestAction>
+ <LaunchAction
+ buildConfiguration = "Debug"
+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+ launchStyle = "0"
+ useCustomWorkingDirectory = "NO"
+ ignoresPersistentStateOnLaunch = "NO"
+ debugDocumentVersioning = "YES"
+ debugServiceExtension = "internal"
+ allowLocationSimulation = "YES">
+ <BuildableProductRunnable
+ runnableDebuggingMode = "0">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "97C146ED1CF9000F007C117D"
+ BuildableName = "Runner.app"
+ BlueprintName = "Runner"
+ ReferencedContainer = "container:Runner.xcodeproj">
+ </BuildableReference>
+ </BuildableProductRunnable>
+ </LaunchAction>
+ <ProfileAction
+ buildConfiguration = "Profile"
+ shouldUseLaunchSchemeArgsEnv = "YES"
+ savedToolIdentifier = ""
+ useCustomWorkingDirectory = "NO"
+ debugDocumentVersioning = "YES">
+ <BuildableProductRunnable
+ runnableDebuggingMode = "0">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "97C146ED1CF9000F007C117D"
+ BuildableName = "Runner.app"
+ BlueprintName = "Runner"
+ ReferencedContainer = "container:Runner.xcodeproj">
+ </BuildableReference>
+ </BuildableProductRunnable>
+ </ProfileAction>
+ <AnalyzeAction
+ buildConfiguration = "Debug">
+ </AnalyzeAction>
+ <ArchiveAction
+ buildConfiguration = "Release"
+ revealArchiveInOrganizer = "YES">
+ </ArchiveAction>
+</Scheme>
diff --git a/packages/audio_service/example/ios/Runner.xcworkspace/contents.xcworkspacedata b/packages/audio_service/example/ios/Runner.xcworkspace/contents.xcworkspacedata
new file mode 100644
index 00000000..21a3cc14
--- /dev/null
+++ b/packages/audio_service/example/ios/Runner.xcworkspace/contents.xcworkspacedata
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Workspace
+ version = "1.0">
+ <FileRef
+ location = "group:Runner.xcodeproj">
+ </FileRef>
+ <FileRef
+ location = "group:Pods/Pods.xcodeproj">
+ </FileRef>
+</Workspace>
diff --git a/packages/audio_service/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/packages/audio_service/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
new file mode 100644
index 00000000..18d98100
--- /dev/null
+++ b/packages/audio_service/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>IDEDidComputeMac32BitWarning</key>
+ <true/>
+</dict>
+</plist>
diff --git a/packages/audio_service/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/packages/audio_service/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings
new file mode 100644
index 00000000..f9b0d7c5
--- /dev/null
+++ b/packages/audio_service/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>PreviewsEnabled</key>
+ <false/>
+</dict>
+</plist>
diff --git a/packages/audio_service/example/ios/Runner/AppDelegate.swift b/packages/audio_service/example/ios/Runner/AppDelegate.swift
new file mode 100644
index 00000000..b6363034
--- /dev/null
+++ b/packages/audio_service/example/ios/Runner/AppDelegate.swift
@@ -0,0 +1,13 @@
+import UIKit
+import Flutter
+
+@main
+@objc class AppDelegate: FlutterAppDelegate {
+ override func application(
+ _ application: UIApplication,
+ didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
+ ) -> Bool {
+ GeneratedPluginRegistrant.register(with: self)
+ return super.application(application, didFinishLaunchingWithOptions: launchOptions)
+ }
+}
diff --git a/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json
new file mode 100644
index 00000000..d36b1fab
--- /dev/null
+++ b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json
@@ -0,0 +1,122 @@
+{
+ "images" : [
+ {
+ "size" : "20x20",
+ "idiom" : "iphone",
+ "filename" : "[email protected]",
+ "scale" : "2x"
+ },
+ {
+ "size" : "20x20",
+ "idiom" : "iphone",
+ "filename" : "[email protected]",
+ "scale" : "3x"
+ },
+ {
+ "size" : "29x29",
+ "idiom" : "iphone",
+ "filename" : "[email protected]",
+ "scale" : "1x"
+ },
+ {
+ "size" : "29x29",
+ "idiom" : "iphone",
+ "filename" : "[email protected]",
+ "scale" : "2x"
+ },
+ {
+ "size" : "29x29",
+ "idiom" : "iphone",
+ "filename" : "[email protected]",
+ "scale" : "3x"
+ },
+ {
+ "size" : "40x40",
+ "idiom" : "iphone",
+ "filename" : "[email protected]",
+ "scale" : "2x"
+ },
+ {
+ "size" : "40x40",
+ "idiom" : "iphone",
+ "filename" : "[email protected]",
+ "scale" : "3x"
+ },
+ {
+ "size" : "60x60",
+ "idiom" : "iphone",
+ "filename" : "[email protected]",
+ "scale" : "2x"
+ },
+ {
+ "size" : "60x60",
+ "idiom" : "iphone",
+ "filename" : "[email protected]",
+ "scale" : "3x"
+ },
+ {
+ "size" : "20x20",
+ "idiom" : "ipad",
+ "filename" : "[email protected]",
+ "scale" : "1x"
+ },
+ {
+ "size" : "20x20",
+ "idiom" : "ipad",
+ "filename" : "[email protected]",
+ "scale" : "2x"
+ },
+ {
+ "size" : "29x29",
+ "idiom" : "ipad",
+ "filename" : "[email protected]",
+ "scale" : "1x"
+ },
+ {
+ "size" : "29x29",
+ "idiom" : "ipad",
+ "filename" : "[email protected]",
+ "scale" : "2x"
+ },
+ {
+ "size" : "40x40",
+ "idiom" : "ipad",
+ "filename" : "[email protected]",
+ "scale" : "1x"
+ },
+ {
+ "size" : "40x40",
+ "idiom" : "ipad",
+ "filename" : "[email protected]",
+ "scale" : "2x"
+ },
+ {
+ "size" : "76x76",
+ "idiom" : "ipad",
+ "filename" : "[email protected]",
+ "scale" : "1x"
+ },
+ {
+ "size" : "76x76",
+ "idiom" : "ipad",
+ "filename" : "[email protected]",
+ "scale" : "2x"
+ },
+ {
+ "size" : "83.5x83.5",
+ "idiom" : "ipad",
+ "filename" : "[email protected]",
+ "scale" : "2x"
+ },
+ {
+ "size" : "1024x1024",
+ "idiom" : "ios-marketing",
+ "filename" : "[email protected]",
+ "scale" : "1x"
+ }
+ ],
+ "info" : {
+ "version" : 1,
+ "author" : "xcode"
+ }
+}
diff --git a/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]
new file mode 100644
index 00000000..dc9ada47
Binary files /dev/null and b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differ
diff --git a/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]
new file mode 100644
index 00000000..28c6bf03
Binary files /dev/null and b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differ
diff --git a/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]
new file mode 100644
index 00000000..2ccbfd96
Binary files /dev/null and b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differ
diff --git a/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]
new file mode 100644
index 00000000..f091b6b0
Binary files /dev/null and b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differ
diff --git a/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]
new file mode 100644
index 00000000..4cde1211
Binary files /dev/null and b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differ
diff --git a/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]
new file mode 100644
index 00000000..d0ef06e7
Binary files /dev/null and b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differ
diff --git a/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]
new file mode 100644
index 00000000..dcdc2306
Binary files /dev/null and b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differ
diff --git a/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]
new file mode 100644
index 00000000..2ccbfd96
Binary files /dev/null and b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differ
diff --git a/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]
new file mode 100644
index 00000000..c8f9ed8f
Binary files /dev/null and b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differ
diff --git a/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]
new file mode 100644
index 00000000..a6d6b860
Binary files /dev/null and b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differ
diff --git a/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]
new file mode 100644
index 00000000..a6d6b860
Binary files /dev/null and b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differ
diff --git a/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]
new file mode 100644
index 00000000..75b2d164
Binary files /dev/null and b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differ
diff --git a/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]
new file mode 100644
index 00000000..c4df70d3
Binary files /dev/null and b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differ
diff --git a/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]
new file mode 100644
index 00000000..6a84f41e
Binary files /dev/null and b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differ
diff --git a/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]
new file mode 100644
index 00000000..d0e1f585
Binary files /dev/null and b/packages/audio_service/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differ
diff --git a/packages/audio_service/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/packages/audio_service/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json
new file mode 100644
index 00000000..0bedcf2f
--- /dev/null
+++ b/packages/audio_service/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json
@@ -0,0 +1,23 @@
+{
+ "images" : [
+ {
+ "idiom" : "universal",
+ "filename" : "LaunchImage.png",
+ "scale" : "1x"
+ },
+ {
+ "idiom" : "universal",
+ "filename" : "[email protected]",
+ "scale" : "2x"
+ },
+ {
+ "idiom" : "universal",
+ "filename" : "[email protected]",
+ "scale" : "3x"
+ }
+ ],
+ "info" : {
+ "version" : 1,
+ "author" : "xcode"
+ }
+}
diff --git a/packages/audio_service/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/packages/audio_service/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png
new file mode 100644
index 00000000..9da19eac
Binary files /dev/null and b/packages/audio_service/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ
diff --git a/packages/audio_service/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/[email protected] b/packages/audio_service/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/[email protected]
new file mode 100644
index 00000000..9da19eac
Binary files /dev/null and b/packages/audio_service/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/[email protected] differ
diff --git a/packages/audio_service/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/[email protected] b/packages/audio_service/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/[email protected]
new file mode 100644
index 00000000..9da19eac
Binary files /dev/null and b/packages/audio_service/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/[email protected] differ
diff --git a/packages/audio_service/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/packages/audio_service/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md
new file mode 100644
index 00000000..89c2725b
--- /dev/null
+++ b/packages/audio_service/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md
@@ -0,0 +1,5 @@
+# Launch Screen Assets
+
+You can customize the launch screen with your own desired assets by replacing the image files in this directory.
+
+You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images.
\ No newline at end of file
diff --git a/packages/audio_service/example/ios/Runner/Base.lproj/LaunchScreen.storyboard b/packages/audio_service/example/ios/Runner/Base.lproj/LaunchScreen.storyboard
new file mode 100644
index 00000000..f2e259c7
--- /dev/null
+++ b/packages/audio_service/example/ios/Runner/Base.lproj/LaunchScreen.storyboard
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="12121" systemVersion="16G29" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
+ <dependencies>
+ <deployment identifier="iOS"/>
+ <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12089"/>
+ </dependencies>
+ <scenes>
+ <!--View Controller-->
+ <scene sceneID="EHf-IW-A2E">
+ <objects>
+ <viewController id="01J-lp-oVM" sceneMemberID="viewController">
+ <layoutGuides>
+ <viewControllerLayoutGuide type="top" id="Ydg-fD-yQy"/>
+ <viewControllerLayoutGuide type="bottom" id="xbc-2k-c8Z"/>
+ </layoutGuides>
+ <view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
+ <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
+ <subviews>
+ <imageView opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" image="LaunchImage" translatesAutoresizingMaskIntoConstraints="NO" id="YRO-k0-Ey4">
+ </imageView>
+ </subviews>
+ <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
+ <constraints>
+ <constraint firstItem="YRO-k0-Ey4" firstAttribute="centerX" secondItem="Ze5-6b-2t3" secondAttribute="centerX" id="1a2-6s-vTC"/>
+ <constraint firstItem="YRO-k0-Ey4" firstAttribute="centerY" secondItem="Ze5-6b-2t3" secondAttribute="centerY" id="4X2-HB-R7a"/>
+ </constraints>
+ </view>
+ </viewController>
+ <placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
+ </objects>
+ <point key="canvasLocation" x="53" y="375"/>
+ </scene>
+ </scenes>
+ <resources>
+ <image name="LaunchImage" width="168" height="185"/>
+ </resources>
+</document>
diff --git a/packages/audio_service/example/ios/Runner/Base.lproj/Main.storyboard b/packages/audio_service/example/ios/Runner/Base.lproj/Main.storyboard
new file mode 100644
index 00000000..f3c28516
--- /dev/null
+++ b/packages/audio_service/example/ios/Runner/Base.lproj/Main.storyboard
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="10117" systemVersion="15F34" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="BYZ-38-t0r">
+ <dependencies>
+ <deployment identifier="iOS"/>
+ <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/>
+ </dependencies>
+ <scenes>
+ <!--Flutter View Controller-->
+ <scene sceneID="tne-QT-ifu">
+ <objects>
+ <viewController id="BYZ-38-t0r" customClass="FlutterViewController" sceneMemberID="viewController">
+ <layoutGuides>
+ <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
+ <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
+ </layoutGuides>
+ <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
+ <rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
+ <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
+ <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
+ </view>
+ </viewController>
+ <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
+ </objects>
+ </scene>
+ </scenes>
+</document>
diff --git a/packages/audio_service/example/ios/Runner/Info.plist b/packages/audio_service/example/ios/Runner/Info.plist
new file mode 100644
index 00000000..9065eebf
--- /dev/null
+++ b/packages/audio_service/example/ios/Runner/Info.plist
@@ -0,0 +1,53 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>$(DEVELOPMENT_LANGUAGE)</string>
+ <key>CFBundleExecutable</key>
+ <string>$(EXECUTABLE_NAME)</string>
+ <key>CFBundleIdentifier</key>
+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string>audio_service_example</string>
+ <key>CFBundlePackageType</key>
+ <string>APPL</string>
+ <key>CFBundleShortVersionString</key>
+ <string>$(FLUTTER_BUILD_NAME)</string>
+ <key>CFBundleSignature</key>
+ <string>????</string>
+ <key>CFBundleVersion</key>
+ <string>$(FLUTTER_BUILD_NUMBER)</string>
+ <key>LSRequiresIPhoneOS</key>
+ <true/>
+ <key>UIBackgroundModes</key>
+ <array>
+ <string>audio</string>
+ </array>
+ <key>UILaunchStoryboardName</key>
+ <string>LaunchScreen</string>
+ <key>UIMainStoryboardFile</key>
+ <string>Main</string>
+ <key>UISupportedInterfaceOrientations</key>
+ <array>
+ <string>UIInterfaceOrientationPortrait</string>
+ <string>UIInterfaceOrientationLandscapeLeft</string>
+ <string>UIInterfaceOrientationLandscapeRight</string>
+ </array>
+ <key>UISupportedInterfaceOrientations~ipad</key>
+ <array>
+ <string>UIInterfaceOrientationPortrait</string>
+ <string>UIInterfaceOrientationPortraitUpsideDown</string>
+ <string>UIInterfaceOrientationLandscapeLeft</string>
+ <string>UIInterfaceOrientationLandscapeRight</string>
+ </array>
+ <key>UIViewControllerBasedStatusBarAppearance</key>
+ <false/>
+ <key>CADisableMinimumFrameDurationOnPhone</key>
+ <true/>
+ <key>UIApplicationSupportsIndirectInputEvents</key>
+ <true/>
+</dict>
+</plist>
diff --git a/packages/audio_service/example/ios/Runner/Runner-Bridging-Header.h b/packages/audio_service/example/ios/Runner/Runner-Bridging-Header.h
new file mode 100644
index 00000000..7335fdf9
--- /dev/null
+++ b/packages/audio_service/example/ios/Runner/Runner-Bridging-Header.h
@@ -0,0 +1 @@
+#import "GeneratedPluginRegistrant.h"
\ No newline at end of file
diff --git a/packages/audio_service/example/lib/common.dart b/packages/audio_service/example/lib/common.dart
new file mode 100644
index 00000000..4fb42820
--- /dev/null
+++ b/packages/audio_service/example/lib/common.dart
@@ -0,0 +1,478 @@
+// ignore_for_file: public_member_api_docs
+
+import 'dart:math';
+
+import 'package:audio_service/audio_service.dart';
+import 'package:flutter/material.dart';
+import 'package:rxdart/rxdart.dart';
+
+class PositionData {
+ final Duration position;
+ final Duration bufferedPosition;
+ final Duration duration;
+
+ PositionData(this.position, this.bufferedPosition, this.duration);
+}
+
+class SeekBar extends StatefulWidget {
+ final Duration duration;
+ final Duration position;
+ final Duration bufferedPosition;
+ final ValueChanged<Duration>? onChanged;
+ final ValueChanged<Duration>? onChangeEnd;
+
+ const SeekBar({
+ super.key,
+ required this.duration,
+ required this.position,
+ this.bufferedPosition = Duration.zero,
+ this.onChanged,
+ this.onChangeEnd,
+ });
+
+ @override
+ SeekBarState createState() => SeekBarState();
+}
+
+class SeekBarState extends State<SeekBar> {
+ double? _dragValue;
+ bool _dragging = false;
+ late SliderThemeData _sliderThemeData;
+
+ @override
+ void didChangeDependencies() {
+ super.didChangeDependencies();
+
+ _sliderThemeData = SliderTheme.of(context).copyWith(
+ trackHeight: 2.0,
+ );
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final value = min(
+ _dragValue ?? widget.position.inMilliseconds.toDouble(),
+ widget.duration.inMilliseconds.toDouble(),
+ );
+ if (_dragValue != null && !_dragging) {
+ _dragValue = null;
+ }
+ return Stack(
+ children: [
+ SliderTheme(
+ data: _sliderThemeData.copyWith(
+ thumbShape: HiddenThumbComponentShape(),
+ activeTrackColor: Colors.blue.shade100,
+ inactiveTrackColor: Colors.grey.shade300,
+ ),
+ child: ExcludeSemantics(
+ child: Slider(
+ min: 0.0,
+ max: widget.duration.inMilliseconds.toDouble(),
+ value: min(widget.bufferedPosition.inMilliseconds.toDouble(),
+ widget.duration.inMilliseconds.toDouble()),
+ onChanged: (value) {},
+ ),
+ ),
+ ),
+ SliderTheme(
+ data: _sliderThemeData.copyWith(
+ inactiveTrackColor: Colors.transparent,
+ ),
+ child: Slider(
+ min: 0.0,
+ max: widget.duration.inMilliseconds.toDouble(),
+ value: value,
+ onChanged: (value) {
+ if (!_dragging) {
+ _dragging = true;
+ }
+ setState(() {
+ _dragValue = value;
+ });
+ if (widget.onChanged != null) {
+ widget.onChanged!(Duration(milliseconds: value.round()));
+ }
+ },
+ onChangeEnd: (value) {
+ if (widget.onChangeEnd != null) {
+ widget.onChangeEnd!(Duration(milliseconds: value.round()));
+ }
+ _dragging = false;
+ },
+ ),
+ ),
+ Positioned(
+ right: 16.0,
+ bottom: 0.0,
+ child: Text(
+ RegExp(r'((^0*[1-9]\d*:)?\d{2}:\d{2})\.\d+$')
+ .firstMatch("$_remaining")
+ ?.group(1) ??
+ '$_remaining',
+ style: Theme.of(context).textTheme.bodySmall),
+ ),
+ ],
+ );
+ }
+
+ Duration get _remaining => widget.duration - widget.position;
+}
+
+class HiddenThumbComponentShape extends SliderComponentShape {
+ @override
+ Size getPreferredSize(bool isEnabled, bool isDiscrete) => Size.zero;
+
+ @override
+ void paint(
+ PaintingContext context,
+ Offset center, {
+ required Animation<double> activationAnimation,
+ required Animation<double> enableAnimation,
+ required bool isDiscrete,
+ required TextPainter labelPainter,
+ required RenderBox parentBox,
+ required SliderThemeData sliderTheme,
+ required TextDirection textDirection,
+ required double value,
+ required double textScaleFactor,
+ required Size sizeWithOverflow,
+ }) {}
+}
+
+class LoggingAudioHandler extends CompositeAudioHandler {
+ LoggingAudioHandler(super.inner) {
+ playbackState.listen((state) {
+ _log('playbackState changed: $state');
+ });
+ queue.listen((queue) {
+ _log('queue changed: $queue');
+ });
+ queueTitle.listen((queueTitle) {
+ _log('queueTitle changed: $queueTitle');
+ });
+ mediaItem.listen((mediaItem) {
+ _log('mediaItem changed: $mediaItem');
+ });
+ ratingStyle.listen((ratingStyle) {
+ _log('ratingStyle changed: $ratingStyle');
+ });
+ androidPlaybackInfo.listen((androidPlaybackInfo) {
+ _log('androidPlaybackInfo changed: $androidPlaybackInfo');
+ });
+ customEvent.listen((dynamic customEventStream) {
+ _log('customEvent changed: $customEventStream');
+ });
+ customState.listen((dynamic customState) {
+ _log('customState changed: $customState');
+ });
+ }
+
+ // TODO: Use logger. Use different log levels.
+ // ignore: avoid_print
+ void _log(String s) => print('----- LOG: $s');
+
+ @override
+ Future<void> prepare() {
+ _log('prepare()');
+ return super.prepare();
+ }
+
+ @override
+ Future<void> prepareFromMediaId(String mediaId,
+ [Map<String, dynamic>? extras]) {
+ _log('prepareFromMediaId($mediaId, $extras)');
+ return super.prepareFromMediaId(mediaId, extras);
+ }
+
+ @override
+ Future<void> prepareFromSearch(String query, [Map<String, dynamic>? extras]) {
+ _log('prepareFromSearch($query, $extras)');
+ return super.prepareFromSearch(query, extras);
+ }
+
+ @override
+ Future<void> prepareFromUri(Uri uri, [Map<String, dynamic>? extras]) {
+ _log('prepareFromSearch($uri, $extras)');
+ return super.prepareFromUri(uri, extras);
+ }
+
+ @override
+ Future<void> play() {
+ _log('play()');
+ return super.play();
+ }
+
+ @override
+ Future<void> playFromMediaId(String mediaId, [Map<String, dynamic>? extras]) {
+ _log('playFromMediaId($mediaId, $extras)');
+ return super.playFromMediaId(mediaId, extras);
+ }
+
+ @override
+ Future<void> playFromSearch(String query, [Map<String, dynamic>? extras]) {
+ _log('playFromSearch($query, $extras)');
+ return super.playFromSearch(query, extras);
+ }
+
+ @override
+ Future<void> playFromUri(Uri uri, [Map<String, dynamic>? extras]) {
+ _log('playFromUri($uri, $extras)');
+ return super.playFromUri(uri, extras);
+ }
+
+ @override
+ Future<void> playMediaItem(MediaItem mediaItem) {
+ _log('playMediaItem($mediaItem)');
+ return super.playMediaItem(mediaItem);
+ }
+
+ @override
+ Future<void> pause() {
+ _log('pause()');
+ return super.pause();
+ }
+
+ @override
+ Future<void> click([MediaButton button = MediaButton.media]) {
+ _log('click($button)');
+ return super.click(button);
+ }
+
+ @override
+ Future<void> stop() {
+ _log('stop()');
+ return super.stop();
+ }
+
+ @override
+ Future<void> addQueueItem(MediaItem mediaItem) {
+ _log('addQueueItem($mediaItem)');
+ return super.addQueueItem(mediaItem);
+ }
+
+ @override
+ Future<void> addQueueItems(List<MediaItem> mediaItems) {
+ _log('addQueueItems($mediaItems)');
+ return super.addQueueItems(mediaItems);
+ }
+
+ @override
+ Future<void> insertQueueItem(int index, MediaItem mediaItem) {
+ _log('insertQueueItem($index, $mediaItem)');
+ return super.insertQueueItem(index, mediaItem);
+ }
+
+ @override
+ Future<void> updateQueue(List<MediaItem> queue) {
+ _log('updateQueue($queue)');
+ return super.updateQueue(queue);
+ }
+
+ @override
+ Future<void> updateMediaItem(MediaItem mediaItem) {
+ _log('updateMediaItem($mediaItem)');
+ return super.updateMediaItem(mediaItem);
+ }
+
+ @override
+ Future<void> removeQueueItem(MediaItem mediaItem) {
+ _log('removeQueueItem($mediaItem)');
+ return super.removeQueueItem(mediaItem);
+ }
+
+ @override
+ Future<void> removeQueueItemAt(int index) {
+ _log('removeQueueItemAt($index)');
+ return super.removeQueueItemAt(index);
+ }
+
+ @override
+ Future<void> skipToNext() {
+ _log('skipToNext()');
+ return super.skipToNext();
+ }
+
+ @override
+ Future<void> skipToPrevious() {
+ _log('skipToPrevious()');
+ return super.skipToPrevious();
+ }
+
+ @override
+ Future<void> fastForward() {
+ _log('fastForward()');
+ return super.fastForward();
+ }
+
+ @override
+ Future<void> rewind() {
+ _log('rewind()');
+ return super.rewind();
+ }
+
+ @override
+ Future<void> skipToQueueItem(int index) {
+ _log('skipToQueueItem($index)');
+ return super.skipToQueueItem(index);
+ }
+
+ @override
+ Future<void> seek(Duration position) {
+ _log('seek($position)');
+ return super.seek(position);
+ }
+
+ @override
+ Future<void> setRating(Rating rating, [Map<String, dynamic>? extras]) {
+ _log('setRating($rating, $extras)');
+ return super.setRating(rating, extras);
+ }
+
+ @override
+ Future<void> setCaptioningEnabled(bool enabled) {
+ _log('setCaptioningEnabled($enabled)');
+ return super.setCaptioningEnabled(enabled);
+ }
+
+ @override
+ Future<void> setRepeatMode(AudioServiceRepeatMode repeatMode) {
+ _log('setRepeatMode($repeatMode)');
+ return super.setRepeatMode(repeatMode);
+ }
+
+ @override
+ Future<void> setShuffleMode(AudioServiceShuffleMode shuffleMode) {
+ _log('setShuffleMode($shuffleMode)');
+ return super.setShuffleMode(shuffleMode);
+ }
+
+ @override
+ Future<void> seekBackward(bool begin) {
+ _log('seekBackward($begin)');
+ return super.seekBackward(begin);
+ }
+
+ @override
+ Future<void> seekForward(bool begin) {
+ _log('seekForward($begin)');
+ return super.seekForward(begin);
+ }
+
+ @override
+ Future<void> setSpeed(double speed) {
+ _log('setSpeed($speed)');
+ return super.setSpeed(speed);
+ }
+
+ @override
+ Future<dynamic> customAction(String name,
+ [Map<String, dynamic>? extras]) async {
+ _log('customAction($name, extras)');
+ final dynamic result = await super.customAction(name, extras);
+ _log('customAction -> $result');
+ return result;
+ }
+
+ @override
+ Future<void> onTaskRemoved() {
+ _log('onTaskRemoved()');
+ return super.onTaskRemoved();
+ }
+
+ @override
+ Future<void> onNotificationDeleted() {
+ _log('onNotificationDeleted()');
+ return super.onNotificationDeleted();
+ }
+
+ @override
+ Future<List<MediaItem>> getChildren(String parentMediaId,
+ [Map<String, dynamic>? options]) async {
+ _log('getChildren($parentMediaId, $options)');
+ final result = await super.getChildren(parentMediaId, options);
+ _log('getChildren -> $result');
+ return result;
+ }
+
+ @override
+ ValueStream<Map<String, dynamic>> subscribeToChildren(String parentMediaId) {
+ _log('subscribeToChildren($parentMediaId)');
+ final result = super.subscribeToChildren(parentMediaId);
+ result.listen((options) {
+ _log('$parentMediaId children changed with options $options');
+ });
+ return result;
+ }
+
+ @override
+ Future<MediaItem?> getMediaItem(String mediaId) async {
+ _log('getMediaItem($mediaId)');
+ final result = await super.getMediaItem(mediaId);
+ _log('getMediaItem -> $result');
+ return result;
+ }
+
+ @override
+ Future<List<MediaItem>> search(String query,
+ [Map<String, dynamic>? extras]) async {
+ _log('search($query, $extras)');
+ final result = await super.search(query, extras);
+ _log('search -> $result');
+ return result;
+ }
+
+ @override
+ Future<void> androidSetRemoteVolume(int volumeIndex) {
+ _log('androidSetRemoteVolume($volumeIndex)');
+ return super.androidSetRemoteVolume(volumeIndex);
+ }
+
+ @override
+ Future<void> androidAdjustRemoteVolume(AndroidVolumeDirection direction) {
+ _log('androidAdjustRemoteVolume($direction)');
+ return super.androidAdjustRemoteVolume(direction);
+ }
+}
+
+void showSliderDialog({
+ required BuildContext context,
+ required String title,
+ required int divisions,
+ required double min,
+ required double max,
+ String valueSuffix = '',
+ // TODO: Replace these two by ValueStream.
+ required double value,
+ required Stream<double> stream,
+ required ValueChanged<double> onChanged,
+}) {
+ showDialog<void>(
+ context: context,
+ builder: (context) => AlertDialog(
+ title: Text(title, textAlign: TextAlign.center),
+ content: StreamBuilder<double>(
+ stream: stream,
+ builder: (context, snapshot) => SizedBox(
+ height: 100.0,
+ child: Column(
+ children: [
+ Text('${snapshot.data?.toStringAsFixed(1)}$valueSuffix',
+ style: const TextStyle(
+ fontFamily: 'Fixed',
+ fontWeight: FontWeight.bold,
+ fontSize: 24.0)),
+ Slider(
+ divisions: divisions,
+ min: min,
+ max: max,
+ value: snapshot.data ?? value,
+ onChanged: onChanged,
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+}
diff --git a/packages/audio_service/example/lib/example_android13.dart b/packages/audio_service/example/lib/example_android13.dart
new file mode 100644
index 00000000..3eb1c84e
--- /dev/null
+++ b/packages/audio_service/example/lib/example_android13.dart
@@ -0,0 +1,243 @@
+// ignore_for_file: public_member_api_docs
+
+// This example demonstrates:
+//
+// - Android 13 fast forward, rewind, and stop working with internal custom actions
+// - Fast forward interval of 30 seconds with custom icons
+// - Android notification with custom "favorite" icon and custom handler.
+//
+// To run this example, use:
+//
+// flutter run -t lib/example_android13.dart
+
+import 'dart:async';
+
+import 'package:audio_service/audio_service.dart';
+import 'package:audio_service_example/common.dart';
+import 'package:flutter/foundation.dart';
+import 'package:flutter/material.dart';
+import 'package:just_audio/just_audio.dart';
+import 'package:rxdart/rxdart.dart';
+
+// You might want to provide this using dependency injection rather than a
+// global variable.
+late AudioHandler _audioHandler;
+
+Future<void> main() async {
+ _audioHandler = await AudioService.init(
+ builder: () => AudioPlayerHandler(),
+ config: const AudioServiceConfig(
+ androidNotificationChannelId: 'com.ryanheise.myapp.channel.audio',
+ androidNotificationChannelName: 'Audio playback',
+ androidNotificationOngoing: true,
+ fastForwardInterval: Duration(seconds: 30),
+ ),
+ );
+ runApp(const MyApp());
+}
+
+class MyApp extends StatelessWidget {
+ const MyApp({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ return MaterialApp(
+ title: 'Demo Android 13',
+ theme: ThemeData(primarySwatch: Colors.blue),
+ home: const MainScreen(),
+ );
+ }
+}
+
+class MainScreen extends StatelessWidget {
+ const MainScreen({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ return Scaffold(
+ appBar: AppBar(
+ title: const Text('Demo for Android 13'),
+ ),
+ body: Center(
+ child: Column(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ // Show media item title
+ StreamBuilder<MediaItem?>(
+ stream: _audioHandler.mediaItem,
+ builder: (context, snapshot) {
+ final mediaItem = snapshot.data;
+ return Text(mediaItem?.title ?? '');
+ },
+ ),
+ // Play/pause/stop buttons.
+ StreamBuilder<bool>(
+ stream: _audioHandler.playbackState
+ .map((state) => state.playing)
+ .distinct(),
+ builder: (context, snapshot) {
+ final playing = snapshot.data ?? false;
+ return Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ _button(Icons.fast_rewind, _audioHandler.rewind),
+ if (playing)
+ _button(Icons.pause, _audioHandler.pause)
+ else
+ _button(Icons.play_arrow, _audioHandler.play),
+ _button(Icons.stop, _audioHandler.stop),
+ _button(Icons.forward_30, _audioHandler.fastForward),
+ ],
+ );
+ },
+ ),
+ // A seek bar.
+ StreamBuilder<MediaState>(
+ stream: _mediaStateStream,
+ builder: (context, snapshot) {
+ final mediaState = snapshot.data;
+ return SeekBar(
+ duration: mediaState?.mediaItem?.duration ?? Duration.zero,
+ position: mediaState?.position ?? Duration.zero,
+ onChangeEnd: (newPosition) {
+ _audioHandler.seek(newPosition);
+ },
+ );
+ },
+ ),
+ // Display the processing state.
+ StreamBuilder<AudioProcessingState>(
+ stream: _audioHandler.playbackState
+ .map((state) => state.processingState)
+ .distinct(),
+ builder: (context, snapshot) {
+ final processingState =
+ snapshot.data ?? AudioProcessingState.idle;
+ return Text(
+ // ignore: deprecated_member_use
+ "Processing state: ${describeEnum(processingState)}");
+ },
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ /// A stream reporting the combined state of the current media item and its
+ /// current position.
+ Stream<MediaState> get _mediaStateStream =>
+ Rx.combineLatest2<MediaItem?, Duration, MediaState>(
+ _audioHandler.mediaItem,
+ AudioService.position,
+ (mediaItem, position) => MediaState(mediaItem, position));
+
+ IconButton _button(IconData iconData, VoidCallback onPressed) => IconButton(
+ icon: Icon(iconData),
+ iconSize: 64.0,
+ onPressed: onPressed,
+ );
+}
+
+class MediaState {
+ final MediaItem? mediaItem;
+ final Duration position;
+
+ MediaState(this.mediaItem, this.position);
+}
+
+/// An [AudioHandler] for playing a single item.
+class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
+ static final _item = MediaItem(
+ id: 'https://s3.amazonaws.com/scifri-episodes/scifri20181123-episode.mp3',
+ album: "Science Friday",
+ title: "A Salute To Head-Scratching Science",
+ artist: "Science Friday and WNYC Studios",
+ duration: const Duration(milliseconds: 5739820),
+ artUri: Uri.parse(
+ 'https://media.wnyc.org/i/1400/1400/l/80/1/ScienceFriday_WNYCStudios_1400.jpg'),
+ );
+
+ final _player = AudioPlayer();
+
+ /// Initialise our audio handler.
+ AudioPlayerHandler() {
+ // So that our clients (the Flutter UI and the system notification) know
+ // what state to display, here we set up our audio handler to broadcast all
+ // playback state changes as they happen via playbackState...
+ _player.playbackEventStream.map(_transformEvent).pipe(playbackState);
+ // ... and also the current media item via mediaItem.
+ mediaItem.add(_item);
+
+ // Load the player.
+ _player.setAudioSource(AudioSource.uri(Uri.parse(_item.id)));
+ }
+
+ // In this simple example, we handle only 4 actions: play, pause, seek and
+ // stop. Any button press from the Flutter UI, notification, lock screen or
+ // headset will be routed through to these 4 methods so that you can handle
+ // your audio playback logic in one place.
+
+ @override
+ Future<void> play() => _player.play();
+
+ @override
+ Future<void> pause() => _player.pause();
+
+ @override
+ Future<void> seek(Duration position) => _player.seek(position);
+
+ @override
+ Future<void> stop() => _player.stop();
+
+ @override
+ Future<dynamic> customAction(String name, [Map<String, dynamic>? extras]) {
+ if (name == 'favorite') {
+ // ignore: avoid_print
+ print('Click favorite, level is ${extras?['level']}');
+ }
+ return super.customAction(name, extras);
+ }
+
+ /// Transform a just_audio event into an audio_service state.
+ ///
+ /// This method is used from the constructor. Every event received from the
+ /// just_audio player will be transformed into an audio_service state so that
+ /// it can be broadcast to audio_service clients.
+ PlaybackState _transformEvent(PlaybackEvent event) {
+ return PlaybackState(
+ controls: [
+ if (_player.playing) MediaControl.pause else MediaControl.play,
+ MediaControl.stop,
+ MediaControl.rewind,
+ const MediaControl(
+ androidIcon: 'drawable/baseline_forward_30_24',
+ label: 'Fast Forward',
+ action: MediaAction.fastForward,
+ ),
+ MediaControl.custom(
+ androidIcon: 'drawable/ic_baseline_favorite_24',
+ label: 'favorite',
+ name: 'favorite',
+ extras: <String, dynamic>{'level': 1}),
+ ],
+ systemActions: const {
+ MediaAction.seek,
+ MediaAction.seekForward,
+ MediaAction.seekBackward,
+ },
+ processingState: const {
+ ProcessingState.idle: AudioProcessingState.idle,
+ ProcessingState.loading: AudioProcessingState.loading,
+ ProcessingState.buffering: AudioProcessingState.buffering,
+ ProcessingState.ready: AudioProcessingState.ready,
+ ProcessingState.completed: AudioProcessingState.completed,
+ }[_player.processingState]!,
+ playing: _player.playing,
+ updatePosition: _player.position,
+ bufferedPosition: _player.bufferedPosition,
+ speed: _player.speed,
+ queueIndex: event.currentIndex,
+ );
+ }
+}
diff --git a/packages/audio_service/example/lib/example_android_songs.dart b/packages/audio_service/example/lib/example_android_songs.dart
new file mode 100644
index 00000000..baaae302
--- /dev/null
+++ b/packages/audio_service/example/lib/example_android_songs.dart
@@ -0,0 +1,591 @@
+// ignore_for_file: public_member_api_docs, dangling_library_doc_comments
+
+/// This example demonstrates working songs on Android, in particular it shows:
+///
+/// * fetching songs from `MediaStore`
+/// * working with content:// URIs
+/// * playing songs from URI
+/// * showing song arts in [AudioService]
+/// * showing song arts in Dart
+///
+/// Plugins, used in this example, other than `audio_service`:
+///
+/// * `android_content_provider` - for song data and arts
+/// * `device_info_plus` - for detecting Android version
+/// * `just_audio` - for playback
+/// * `permission_handler` - for asking for permissions to read
+/// the device storage
+///
+/// In Android there are 3 different ways of loading a song art:
+///
+/// 1. On any Android version:
+/// using ContentResolver and art content:// URI - this is what [AudioService] supports
+/// out of the box.
+/// You can see this being used in [Song.toMediaItem].
+///
+/// 2. On Android 10 and above only:
+/// using [AndroidContentResolver.loadThumbnail] on the song content:// URI in the `MediaStore`,
+/// and NOT the art content:// URI.
+/// Used in [SongArt] widget.
+///
+/// 3. On Android 9 and below only:
+/// using [Song.artPath], which contains a direct path to the art file, and
+/// NOT the art content:// URI.
+/// Used in [SongArt] widget.
+///
+/// The reasons the methods 2 and 3 are even mentioned here are:
+///
+/// * because they are a more performant way of loading the thumbnails
+/// from `MediaStore`
+/// * because [AndroidContentResolver] does not support (yet)
+/// `ContentResolver.openFileDescriptor`
+///
+/// To run this example, use:
+///
+/// flutter run -t lib/example_android_songs.dart
+
+import 'dart:io';
+import 'dart:typed_data';
+
+import 'package:audio_service/audio_service.dart';
+import 'package:flutter/material.dart';
+import 'package:android_content_provider/android_content_provider.dart';
+import 'package:device_info_plus/device_info_plus.dart';
+import 'package:just_audio/just_audio.dart';
+import 'package:rxdart/rxdart.dart';
+import 'package:permission_handler/permission_handler.dart';
+
+// You might want to provide this using dependency injection rather than a
+// global variable.
+late AudioPlayerHandler _audioHandler;
+late int sdkInt;
+List<Song>? _songs;
+final albumArtPaths = <int, String>{};
+
+/// Whether running on scoped storage (Android 10 and above),
+/// and should use bytes to load album arts from `MediaStore`.
+bool get useScopedStorage => sdkInt >= 29;
+
+Future<void> main() async {
+ WidgetsFlutterBinding.ensureInitialized();
+
+ DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
+ AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
+ sdkInt = androidInfo.version.sdkInt;
+
+ _audioHandler = await AudioService.init(
+ builder: () => AudioPlayerHandler(),
+ config: const AudioServiceConfig(
+ androidNotificationChannelId: 'com.ryanheise.myapp.channel.audio',
+ androidNotificationChannelName: 'Audio playback',
+ androidNotificationOngoing: true,
+ ),
+ );
+ runApp(const MyApp());
+}
+
+class MyApp extends StatelessWidget {
+ const MyApp({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ return MaterialApp(
+ title: 'Audio Service Demo',
+ theme: ThemeData(primarySwatch: Colors.blue),
+ home: const MainScreen(),
+ );
+ }
+}
+
+class MainScreen extends StatefulWidget {
+ const MainScreen({super.key});
+
+ @override
+ State<MainScreen> createState() => _MainScreenState();
+}
+
+class _MainScreenState extends State<MainScreen> {
+ PermissionStatus? _permissionStatus;
+
+ @override
+ void initState() {
+ super.initState();
+ _fetch();
+ }
+
+ Future<void> _fetch() async {
+ _permissionStatus = await Permission.storage.request();
+ if (mounted) {
+ setState(() {
+ // Update to maybe show progress indicator.
+ });
+ }
+ if (_permissionStatus == PermissionStatus.granted) {
+ await _fetchSongs();
+ await _fetchArts();
+ if (_songs!.isNotEmpty) {
+ _audioHandler.init();
+ }
+ } else if (_permissionStatus == PermissionStatus.permanentlyDenied) {
+ await openAppSettings();
+ }
+ if (mounted) {
+ setState(() {
+ // Update to show the fetch result.
+ });
+ }
+ }
+
+ Future<void> _fetchSongs() async {
+ final cursor = await AndroidContentResolver.instance.query(
+ // MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
+ uri: 'content://media/external/audio/media',
+ projection: Song.mediaStoreProjection,
+ selection: 'is_music != 0',
+ selectionArgs: null,
+ sortOrder: null,
+ );
+ try {
+ final songCount =
+ (await cursor!.batchedGet().getCount().commit()).first as int;
+ final batch = Song.createBatch(cursor);
+ final songsData = await batch.commitRange(0, songCount);
+ _songs = songsData.map((data) => Song.fromMediaStore(data)).toList();
+ } finally {
+ cursor?.close();
+ }
+ }
+
+ Future<void> _fetchArts() async {
+ if (useScopedStorage) {
+ return;
+ }
+ final cursor = await AndroidContentResolver.instance.query(
+ // MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI
+ uri: 'content://media/external/audio/albums',
+ projection: const ['_id', 'album_art'],
+ selection: 'album_art != 0',
+ selectionArgs: null,
+ sortOrder: null,
+ );
+ try {
+ final albumCount =
+ (await cursor!.batchedGet().getCount().commit()).first as int;
+ final batch = cursor.batchedGet()
+ ..getInt(0)
+ ..getString(1);
+ final albumsData = await batch.commitRange(0, albumCount);
+ for (final data in albumsData) {
+ albumArtPaths[data.first as int] = data.last as String;
+ }
+ } finally {
+ cursor?.close();
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final Widget child;
+ if (_permissionStatus == null) {
+ child = const Scaffold();
+ } else if (_permissionStatus != PermissionStatus.granted) {
+ child = Scaffold(
+ body: Center(
+ child: ElevatedButton(
+ onPressed: _fetch,
+ child: const Text('Grant storage permissions'),
+ ),
+ ),
+ );
+ } else if (_permissionStatus == PermissionStatus.granted &&
+ _songs == null) {
+ child = const Center(
+ child: CircularProgressIndicator(),
+ );
+ } else if (_songs != null && _songs!.isEmpty) {
+ child = Center(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ const Text('There is no music on your device'),
+ ElevatedButton(
+ onPressed: _fetch,
+ child: const Text('Refetch'),
+ ),
+ ],
+ ),
+ );
+ } else {
+ child = const SongListScreen();
+ }
+ return Scaffold(
+ body: child,
+ );
+ }
+}
+
+class SongListScreen extends StatelessWidget {
+ const SongListScreen({super.key});
+
+ IconButton _button(IconData iconData, VoidCallback onPressed) => IconButton(
+ icon: Icon(iconData),
+ onPressed: onPressed,
+ );
+
+ @override
+ Widget build(BuildContext context) {
+ return Scaffold(
+ appBar: AppBar(
+ title: const Text('Audio Service Demo'),
+ ),
+ bottomNavigationBar: Material(
+ color: Colors.white,
+ elevation: 12,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ _buildControls(),
+ _buildCurrentSong(),
+ ],
+ ),
+ ),
+ body: Scrollbar(
+ interactive: true,
+ child: ListView.builder(
+ itemCount: _songs!.length,
+ itemBuilder: (context, index) {
+ final song = _songs![index];
+ return SongTile(song: song);
+ },
+ ),
+ ),
+ );
+ }
+
+ Widget _buildControls() {
+ return StreamBuilder<bool>(
+ stream:
+ _audioHandler.playbackState.map((state) => state.playing).distinct(),
+ builder: (context, snapshot) {
+ final playing = snapshot.data ?? false;
+ return Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ _button(Icons.skip_previous, _audioHandler.skipToPrevious),
+ if (playing)
+ _button(Icons.pause, _audioHandler.pause)
+ else
+ _button(Icons.play_arrow, _audioHandler.play),
+ _button(Icons.stop, _audioHandler.stop),
+ _button(Icons.skip_next, _audioHandler.skipToNext),
+ ],
+ );
+ },
+ );
+ }
+
+ Widget _buildCurrentSong() {
+ return StreamBuilder<Song?>(
+ stream: _audioHandler.currentSong,
+ builder: (context, snapshot) {
+ if (!snapshot.hasData) {
+ return const SizedBox();
+ }
+ final song = snapshot.data!;
+ return SongTile(
+ song: song,
+ tappable: false,
+ );
+ },
+ );
+ }
+}
+
+class SongTile extends StatelessWidget {
+ const SongTile({
+ super.key,
+ required this.song,
+ this.tappable = true,
+ });
+
+ final Song song;
+ final bool tappable;
+
+ @override
+ Widget build(BuildContext context) {
+ return ListTile(
+ title: Text(song.title),
+ subtitle: Text(song.artist),
+ leading: SongArt(song: song),
+ onTap: !tappable
+ ? null
+ : () {
+ _audioHandler.setSong(song);
+ _audioHandler.play();
+ },
+ );
+ }
+}
+
+/// Shows local song art from Android `MediaStore`.
+///
+/// On Android 10 and above album arts should be fetched with
+/// a special method [AndroidContentResolver.loadThumbnail].
+///
+/// Lower Android 10 album arts ared displayed directly from the file path
+/// of album art from [Song.artPath] (which was removed in Android 10).
+///
+/// See the comment at the top of the example for the full context.
+class SongArt extends StatefulWidget {
+ const SongArt({super.key, required this.song});
+
+ final Song song;
+
+ @override
+ State<SongArt> createState() => _SongArtState();
+}
+
+class _SongArtState extends State<SongArt> {
+ CancellationSignal? _loadSignal;
+ Uint8List? _bytes;
+ bool loaded = false;
+
+ static const int _artSize = 60;
+
+ @override
+ void didChangeDependencies() {
+ super.didChangeDependencies();
+ _fetchArt();
+ }
+
+ @override
+ void didUpdateWidget(covariant SongArt oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ if (widget.song.id != oldWidget.song.id) {
+ _fetchArt();
+ }
+ }
+
+ int getCacheSize() {
+ final devicePixelRatio = MediaQuery.of(context).devicePixelRatio;
+ return (_artSize * devicePixelRatio).toInt();
+ }
+
+ Future<void> _fetchArt() async {
+ if (!useScopedStorage) {
+ return;
+ }
+ _loadSignal?.cancel();
+ _loadSignal = CancellationSignal();
+ final cacheSize = getCacheSize();
+ try {
+ _bytes = await AndroidContentResolver.instance.loadThumbnail(
+ uri: widget.song.uri,
+ width: cacheSize,
+ height: cacheSize,
+ cancellationSignal: _loadSignal,
+ );
+ } catch (e) {
+ _bytes = null;
+ }
+ if (mounted) {
+ setState(() {
+ loaded = true;
+ });
+ }
+ }
+
+ @override
+ void dispose() {
+ _loadSignal?.cancel();
+ super.dispose();
+ }
+
+ Widget _buildPlaceholder() => Container(
+ color: Colors.blue,
+ child: const Icon(
+ Icons.music_note,
+ color: Colors.white,
+ size: _artSize / 1.5,
+ ),
+ );
+
+ @override
+ Widget build(BuildContext context) {
+ final Widget child;
+ if (useScopedStorage) {
+ final cacheSize = getCacheSize();
+ child = !loaded
+ ? SizedBox.square(dimension: _artSize.toDouble())
+ : _bytes == null
+ ? _buildPlaceholder()
+ : Image.memory(
+ _bytes!,
+ cacheHeight: cacheSize,
+ cacheWidth: cacheSize,
+ );
+ } else {
+ final artPath = widget.song.artPath;
+ var file = artPath == null ? null : File(artPath);
+ if (artPath == null || !file!.existsSync()) {
+ child = _buildPlaceholder();
+ } else {
+ final cacheSize = getCacheSize();
+ child = Image.file(
+ file,
+ cacheHeight: cacheSize,
+ cacheWidth: cacheSize,
+ );
+ }
+ }
+ return SizedBox.square(
+ dimension: _artSize.toDouble(),
+ child: child,
+ );
+ }
+}
+
+class AudioPlayerHandler extends BaseAudioHandler with QueueHandler {
+ final _player = AudioPlayer();
+ final currentSong = BehaviorSubject<Song>();
+
+ void init() {
+ // Propagate all events from the audio player to AudioService clients.
+ _player.playbackEventStream.listen(_broadcastState);
+ // Put the songs into queue.
+ queue.add(_songs!.map((song) => song.toMediaItem()).toList());
+ _player.processingStateStream.listen((state) {
+ if (state == ProcessingState.completed) skipToNext();
+ });
+
+ setSong(_songs!.first);
+ }
+
+ Future<void> setSong(Song song) async {
+ currentSong.add(song);
+ mediaItem.add(song.toMediaItem());
+ await _player.setAudioSource(
+ ProgressiveAudioSource(Uri.parse(song.uri)),
+ );
+ }
+
+ @override
+ Future<void> play() => _player.play();
+
+ @override
+ Future<void> pause() => _player.pause();
+
+ @override
+ Future<void> seek(Duration position) => _player.seek(position);
+
+ @override
+ Future<void> stop() async {
+ await _player.stop();
+ await playbackState.firstWhere(
+ (state) => state.processingState == AudioProcessingState.idle);
+ }
+
+ @override
+ Future<void> skipToQueueItem(int index) async {
+ if (index <= 0 || index >= queue.value.length) {
+ // TODO: remove this when QueueHandler._skip is fixed
+ return;
+ }
+ await setSong(_songs![index]);
+ }
+
+ /// Broadcasts the current state to all clients.
+ void _broadcastState(PlaybackEvent event) {
+ final playing = _player.playing;
+ final queueIndex = _songs!.indexOf(currentSong.value);
+ playbackState.add(playbackState.value.copyWith(
+ controls: [
+ MediaControl.skipToPrevious,
+ if (playing) MediaControl.pause else MediaControl.play,
+ MediaControl.stop,
+ MediaControl.skipToNext,
+ ],
+ systemActions: const {
+ MediaAction.seek,
+ MediaAction.seekForward,
+ MediaAction.seekBackward,
+ },
+ androidCompactActionIndices: const [0, 1, 3],
+ processingState: const {
+ ProcessingState.idle: AudioProcessingState.idle,
+ ProcessingState.loading: AudioProcessingState.loading,
+ ProcessingState.buffering: AudioProcessingState.buffering,
+ ProcessingState.ready: AudioProcessingState.ready,
+ ProcessingState.completed: AudioProcessingState.completed,
+ }[_player.processingState]!,
+ playing: playing,
+ updatePosition: _player.position,
+ bufferedPosition: _player.bufferedPosition,
+ speed: _player.speed,
+ queueIndex: queueIndex,
+ ));
+ }
+}
+
+class Song {
+ final int id;
+ final String? album;
+ final int albumId;
+ final String artist;
+ final String title;
+
+ /// Actual art file path, if any.
+ String? get artPath => albumArtPaths[albumId];
+
+ /// The content URI of the song for playback.
+ String get uri => 'content://media/external/audio/media/$id';
+
+ /// The content URI of the art.
+ String get artUri => 'content://media/external/audio/media/$id/albumart';
+
+ const Song({
+ required this.id,
+ required this.album,
+ required this.albumId,
+ required this.artist,
+ required this.title,
+ });
+
+ /// Converts the song info to [AudioService] media item.
+ MediaItem toMediaItem() => MediaItem(
+ id: id.toString(),
+ album: album,
+ artist: artist,
+ title: title,
+ artUri: Uri.parse(artUri),
+ extras: <String, dynamic>{
+ 'loadThumbnailUri': uri,
+ },
+ );
+
+ static const mediaStoreProjection = [
+ '_id',
+ 'album',
+ 'album_id',
+ 'artist',
+ 'title',
+ ];
+
+ /// Creates a song from data retrieved from the MediaStore.
+ factory Song.fromMediaStore(List<Object?> data) => Song(
+ id: data[0] as int,
+ album: data[1] as String?,
+ albumId: data[2] as int,
+ artist: data[3] as String,
+ title: data[4] as String,
+ );
+
+ /// Returns a markup of what data to get from the cursor.
+ static NativeCursorGetBatch createBatch(NativeCursor cursor) =>
+ cursor.batchedGet()
+ ..getInt(0)
+ ..getString(1)
+ ..getInt(2)
+ ..getString(3)
+ ..getString(4);
+}
diff --git a/packages/audio_service/example/lib/example_multiple_handlers.dart b/packages/audio_service/example/lib/example_multiple_handlers.dart
new file mode 100644
index 00000000..6e6dad9a
--- /dev/null
+++ b/packages/audio_service/example/lib/example_multiple_handlers.dart
@@ -0,0 +1,698 @@
+// ignore_for_file: public_member_api_docs, avoid_print
+
+// This example demonstrates:
+//
+// - queues/playlists
+// - switching between audio handlers (audio player / text-to-speech player)
+// - logging
+// - custom actions
+// - custom events
+// - Android 11 media session resumption
+// - Android Auto
+//
+// To run this example, use:
+//
+// flutter run -t lib/example_multiple_handlers.dart
+
+import 'dart:async';
+
+import 'package:audio_service/audio_service.dart';
+import 'package:audio_service_example/common.dart';
+import 'package:audio_session/audio_session.dart';
+import 'package:flutter/foundation.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_tts/flutter_tts.dart';
+import 'package:just_audio/just_audio.dart';
+import 'package:rxdart/rxdart.dart';
+
+// You might want to provide this using dependency injection rather than a
+// global variable.
+late AudioHandler _audioHandler;
+
+/// Extension methods for our custom actions.
+extension DemoAudioHandler on AudioHandler {
+ Future<void> switchToHandler(int? index) async {
+ if (index == null) return;
+ await _audioHandler
+ .customAction('switchToHandler', <String, dynamic>{'index': index});
+ }
+}
+
+Future<void> main() async {
+ _audioHandler = await AudioService.init(
+ builder: () => LoggingAudioHandler(MainSwitchHandler([
+ AudioPlayerHandler(),
+ TextPlayerHandler(),
+ ])),
+ config: const AudioServiceConfig(
+ androidNotificationChannelId: 'com.ryanheise.myapp.channel.audio',
+ androidNotificationChannelName: 'Audio playback',
+ androidNotificationOngoing: true,
+ ),
+ );
+ // Log async errors from the platform.
+ AudioService.asyncError.listen((e) => print('Async error: $e'));
+ runApp(const MyApp());
+}
+
+/// The app widget
+class MyApp extends StatelessWidget {
+ const MyApp({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ return MaterialApp(
+ title: 'Audio Service Demo',
+ theme: ThemeData(primarySwatch: Colors.blue),
+ home: const MainScreen(),
+ );
+ }
+}
+
+/// The main screen.
+class MainScreen extends StatelessWidget {
+ static const _handlerNames = [
+ 'Audio Player',
+ 'Text-To-Speech',
+ ];
+
+ const MainScreen({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ return Scaffold(
+ appBar: AppBar(
+ title: const Text('Audio Service Demo'),
+ ),
+ body: Center(
+ child: Column(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ // Queue display/controls.
+ StreamBuilder<QueueState>(
+ stream: _queueStateStream,
+ builder: (context, snapshot) {
+ final queueState = snapshot.data;
+ final queue = queueState?.queue ?? const [];
+ final mediaItem = queueState?.mediaItem;
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ StreamBuilder<dynamic>(
+ stream: _audioHandler.customState,
+ builder: (context, snapshot) {
+ final handlerIndex =
+ (snapshot.data?.handlerIndex as int?) ?? 0;
+ return DropdownButton<int>(
+ value: handlerIndex,
+ items: [
+ for (var i = 0; i < _handlerNames.length; i++)
+ DropdownMenuItem<int>(
+ value: i,
+ child: Text(_handlerNames[i]),
+ ),
+ ],
+ onChanged: _audioHandler.switchToHandler,
+ );
+ },
+ ),
+ if (queue.isNotEmpty)
+ Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ IconButton(
+ icon: const Icon(Icons.skip_previous),
+ iconSize: 64.0,
+ onPressed: mediaItem == queue.first
+ ? null
+ : _audioHandler.skipToPrevious,
+ ),
+ IconButton(
+ icon: const Icon(Icons.skip_next),
+ iconSize: 64.0,
+ onPressed: mediaItem == queue.last
+ ? null
+ : _audioHandler.skipToNext,
+ ),
+ ],
+ ),
+ if (mediaItem?.title != null) Text(mediaItem!.title),
+ ],
+ );
+ },
+ ),
+ // Play/pause/stop buttons.
+ StreamBuilder<bool>(
+ stream: _audioHandler.playbackState
+ .map((state) => state.playing)
+ .distinct(),
+ builder: (context, snapshot) {
+ final playing = snapshot.data ?? false;
+ return Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ if (playing) _pauseButton() else _playButton(),
+ _stopButton(),
+ ],
+ );
+ },
+ ),
+ // A seek bar.
+ StreamBuilder<MediaState>(
+ stream: _mediaStateStream,
+ builder: (context, snapshot) {
+ final mediaState = snapshot.data;
+ return SeekBar(
+ duration: mediaState?.mediaItem?.duration ?? Duration.zero,
+ position: mediaState?.position ?? Duration.zero,
+ onChangeEnd: (newPosition) {
+ _audioHandler.seek(newPosition);
+ },
+ );
+ },
+ ),
+ // Display the processing state.
+ StreamBuilder<AudioProcessingState>(
+ stream: _audioHandler.playbackState
+ .map((state) => state.processingState)
+ .distinct(),
+ builder: (context, snapshot) {
+ final processingState =
+ snapshot.data ?? AudioProcessingState.idle;
+ return Text(
+ // ignore: deprecated_member_use
+ "Processing state: ${describeEnum(processingState)}");
+ },
+ ),
+ // Display the latest custom event.
+ StreamBuilder<dynamic>(
+ stream: _audioHandler.customEvent,
+ builder: (context, snapshot) {
+ return Text("custom event: ${snapshot.data}");
+ },
+ ),
+ // Display the notification click status.
+ StreamBuilder<bool>(
+ stream: AudioService.notificationClicked,
+ builder: (context, snapshot) {
+ return Text(
+ 'Notification Click Status: ${snapshot.data}',
+ );
+ },
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ /// A stream reporting the combined state of the current media item and its
+ /// current position.
+ Stream<MediaState> get _mediaStateStream =>
+ Rx.combineLatest2<MediaItem?, Duration, MediaState>(
+ _audioHandler.mediaItem,
+ AudioService.position,
+ (mediaItem, position) => MediaState(mediaItem, position));
+
+ /// A stream reporting the combined state of the current queue and the current
+ /// media item within that queue.
+ Stream<QueueState> get _queueStateStream =>
+ Rx.combineLatest2<List<MediaItem>, MediaItem?, QueueState>(
+ _audioHandler.queue,
+ _audioHandler.mediaItem,
+ (queue, mediaItem) => QueueState(queue, mediaItem));
+
+ IconButton _playButton() => IconButton(
+ icon: const Icon(Icons.play_arrow),
+ iconSize: 64.0,
+ onPressed: _audioHandler.play,
+ );
+
+ IconButton _pauseButton() => IconButton(
+ icon: const Icon(Icons.pause),
+ iconSize: 64.0,
+ onPressed: _audioHandler.pause,
+ );
+
+ IconButton _stopButton() => IconButton(
+ icon: const Icon(Icons.stop),
+ iconSize: 64.0,
+ onPressed: _audioHandler.stop,
+ );
+}
+
+class QueueState {
+ final List<MediaItem> queue;
+ final MediaItem? mediaItem;
+
+ QueueState(this.queue, this.mediaItem);
+}
+
+class MediaState {
+ final MediaItem? mediaItem;
+ final Duration position;
+
+ MediaState(this.mediaItem, this.position);
+}
+
+class CustomEvent {
+ final int handlerIndex;
+
+ CustomEvent(this.handlerIndex);
+}
+
+class MainSwitchHandler extends SwitchAudioHandler {
+ final List<AudioHandler> handlers;
+ @override
+ BehaviorSubject<dynamic> customState =
+ BehaviorSubject<dynamic>.seeded(CustomEvent(0));
+
+ MainSwitchHandler(this.handlers) : super(handlers.first) {
+ // Configure the app's audio category and attributes for speech.
+ AudioSession.instance.then((session) {
+ session.configure(const AudioSessionConfiguration.speech());
+ });
+ }
+
+ @override
+ Future<dynamic> customAction(String name,
+ [Map<String, dynamic>? extras]) async {
+ switch (name) {
+ case 'switchToHandler':
+ stop();
+ final index = extras!['index'] as int;
+ inner = handlers[index];
+ customState.add(CustomEvent(index));
+ return null;
+ default:
+ return super.customAction(name, extras);
+ }
+ }
+}
+
+/// An [AudioHandler] for playing a list of podcast episodes.
+class AudioPlayerHandler extends BaseAudioHandler
+ with QueueHandler, SeekHandler {
+ // ignore: close_sinks
+ final BehaviorSubject<List<MediaItem>> _recentSubject =
+ BehaviorSubject.seeded(<MediaItem>[]);
+ final _mediaLibrary = MediaLibrary();
+ final _player = AudioPlayer();
+
+ int? get index => _player.currentIndex;
+
+ AudioPlayerHandler() {
+ _init();
+ }
+
+ Future<void> _init() async {
+ // Load and broadcast the queue
+ queue.add(_mediaLibrary.items[MediaLibrary.albumsRootId]!);
+ // For Android 11, record the most recent item so it can be resumed.
+ mediaItem
+ .whereType<MediaItem>()
+ .listen((item) => _recentSubject.add([item]));
+ // Broadcast media item changes.
+ _player.currentIndexStream.listen((index) {
+ if (index != null) mediaItem.add(queue.value[index]);
+ });
+ // Propagate all events from the audio player to AudioService clients.
+ _player.playbackEventStream.listen(_broadcastState);
+ // In this example, the service stops when reaching the end.
+ _player.processingStateStream.listen((state) {
+ if (state == ProcessingState.completed) stop();
+ });
+ try {
+ // After a cold restart (on Android), _player.load jumps straight from
+ // the loading state to the completed state. Inserting a delay makes it
+ // work. Not sure why!
+ //await Future.delayed(Duration(seconds: 2)); // magic delay
+ await _player.setAudioSource(ConcatenatingAudioSource(
+ children: queue.value
+ .map((item) => AudioSource.uri(Uri.parse(item.id)))
+ .toList(),
+ ));
+ } catch (e) {
+ print("Error: $e");
+ }
+ }
+
+ @override
+ Future<List<MediaItem>> getChildren(String parentMediaId,
+ [Map<String, dynamic>? options]) async {
+ switch (parentMediaId) {
+ case AudioService.recentRootId:
+ // When the user resumes a media session, tell the system what the most
+ // recently played item was.
+ return _recentSubject.value;
+ default:
+ // Allow client to browse the media library.
+ return _mediaLibrary.items[parentMediaId]!;
+ }
+ }
+
+ @override
+ ValueStream<Map<String, dynamic>> subscribeToChildren(String parentMediaId) {
+ switch (parentMediaId) {
+ case AudioService.recentRootId:
+ final stream = _recentSubject.map((_) => <String, dynamic>{});
+ return _recentSubject.hasValue
+ ? stream.shareValueSeeded(<String, dynamic>{})
+ : stream.shareValue();
+ default:
+ return Stream.value(_mediaLibrary.items[parentMediaId])
+ .map((_) => <String, dynamic>{})
+ .shareValue();
+ }
+ }
+
+ @override
+ Future<void> skipToQueueItem(int index) async {
+ // Then default implementations of skipToNext and skipToPrevious provided by
+ // the [QueueHandler] mixin will delegate to this method.
+ if (index < 0 || index >= queue.value.length) return;
+ // This jumps to the beginning of the queue item at newIndex.
+ _player.seek(Duration.zero, index: index);
+ // Demonstrate custom events.
+ customEvent.add('skip to $index');
+ }
+
+ @override
+ Future<void> play() => _player.play();
+
+ @override
+ Future<void> pause() => _player.pause();
+
+ @override
+ Future<void> seek(Duration position) => _player.seek(position);
+
+ @override
+ Future<void> stop() async {
+ await _player.stop();
+ await playbackState.firstWhere(
+ (state) => state.processingState == AudioProcessingState.idle);
+ }
+
+ /// Broadcasts the current state to all clients.
+ void _broadcastState(PlaybackEvent event) {
+ final playing = _player.playing;
+ playbackState.add(playbackState.value.copyWith(
+ controls: [
+ MediaControl.skipToPrevious,
+ if (playing) MediaControl.pause else MediaControl.play,
+ MediaControl.stop,
+ MediaControl.skipToNext,
+ ],
+ systemActions: const {
+ MediaAction.seek,
+ MediaAction.seekForward,
+ MediaAction.seekBackward,
+ },
+ androidCompactActionIndices: const [0, 1, 3],
+ processingState: const {
+ ProcessingState.idle: AudioProcessingState.idle,
+ ProcessingState.loading: AudioProcessingState.loading,
+ ProcessingState.buffering: AudioProcessingState.buffering,
+ ProcessingState.ready: AudioProcessingState.ready,
+ ProcessingState.completed: AudioProcessingState.completed,
+ }[_player.processingState]!,
+ playing: playing,
+ updatePosition: _player.position,
+ bufferedPosition: _player.bufferedPosition,
+ speed: _player.speed,
+ queueIndex: event.currentIndex,
+ ));
+ }
+}
+
+/// Provides access to a library of media items. In your app, this could come
+/// from a database or web service.
+class MediaLibrary {
+ static const albumsRootId = 'albums';
+
+ final items = <String, List<MediaItem>>{
+ AudioService.browsableRootId: const [
+ MediaItem(
+ id: albumsRootId,
+ title: "Albums",
+ playable: false,
+ ),
+ ],
+ albumsRootId: [
+ MediaItem(
+ id: 'https://s3.amazonaws.com/scifri-episodes/scifri20181123-episode.mp3',
+ album: "Science Friday",
+ title: "A Salute To Head-Scratching Science",
+ artist: "Science Friday and WNYC Studios",
+ duration: const Duration(milliseconds: 5739820),
+ artUri: Uri.parse(
+ 'https://media.wnyc.org/i/1400/1400/l/80/1/ScienceFriday_WNYCStudios_1400.jpg'),
+ ),
+ MediaItem(
+ id: 'https://s3.amazonaws.com/scifri-segments/scifri201711241.mp3',
+ album: "Science Friday",
+ title: "From Cat Rheology To Operatic Incompetence",
+ artist: "Science Friday and WNYC Studios",
+ duration: const Duration(milliseconds: 2856950),
+ artUri: Uri.parse(
+ 'https://media.wnyc.org/i/1400/1400/l/80/1/ScienceFriday_WNYCStudios_1400.jpg'),
+ ),
+ ],
+ };
+}
+
+/// This task defines logic for speaking a sequence of numbers using
+/// text-to-speech.
+class TextPlayerHandler extends BaseAudioHandler with QueueHandler {
+ final _tts = Tts();
+ final _sleeper = Sleeper();
+ Completer<void>? _completer;
+ var _index = 0;
+ bool _interrupted = false;
+ var _running = false;
+
+ bool get _playing => playbackState.value.playing;
+
+ TextPlayerHandler() {
+ _init();
+ }
+
+ Future<void> _init() async {
+ final session = await AudioSession.instance;
+ // Handle audio interruptions.
+ session.interruptionEventStream.listen((event) {
+ if (event.begin) {
+ if (_playing) {
+ pause();
+ _interrupted = true;
+ }
+ } else {
+ switch (event.type) {
+ case AudioInterruptionType.pause:
+ case AudioInterruptionType.duck:
+ if (!_playing && _interrupted) {
+ play();
+ }
+ break;
+ case AudioInterruptionType.unknown:
+ break;
+ }
+ _interrupted = false;
+ }
+ });
+ // Handle unplugged headphones.
+ session.becomingNoisyEventStream.listen((_) {
+ if (_playing) pause();
+ });
+ queue.add(List.generate(
+ 10,
+ (i) => MediaItem(
+ id: 'tts_${i + 1}',
+ album: 'Numbers',
+ title: 'Number ${i + 1}',
+ artist: 'Sample Artist',
+ extras: <String, int>{'number': i + 1},
+ duration: const Duration(seconds: 1),
+ )));
+ }
+
+ Future<void> run() async {
+ _completer = Completer<void>();
+ _running = true;
+ while (_running) {
+ try {
+ if (_playing) {
+ mediaItem.add(queue.value[_index]);
+ playbackState.add(playbackState.value.copyWith(
+ updatePosition: Duration.zero,
+ queueIndex: _index,
+ ));
+ AudioService.androidForceEnableMediaButtons();
+ await Future.wait([
+ _tts.speak('${mediaItem.value!.extras!["number"]}'),
+ _sleeper.sleep(const Duration(seconds: 1)),
+ ]);
+ if (_index + 1 < queue.value.length) {
+ _index++;
+ } else {
+ _running = false;
+ }
+ } else {
+ await _sleeper.sleep();
+ }
+ // ignore: empty_catches
+ } on SleeperInterruptedException {
+ // ignore: empty_catches
+ } on TtsInterruptedException {}
+ }
+ _index = 0;
+ mediaItem.add(queue.value[_index]);
+ playbackState.add(playbackState.value.copyWith(
+ updatePosition: Duration.zero,
+ ));
+ if (playbackState.value.processingState != AudioProcessingState.idle) {
+ stop();
+ }
+ _completer?.complete();
+ _completer = null;
+ }
+
+ @override
+ Future<void> skipToQueueItem(int index) async {
+ _index = index;
+ _signal();
+ }
+
+ @override
+ Future<void> play() async {
+ if (_playing) return;
+ final session = await AudioSession.instance;
+ // flutter_tts doesn't activate the session, so we do it here. This
+ // allows the app to stop other apps from playing audio while we are
+ // playing audio.
+ if (await session.setActive(true)) {
+ // If we successfully activated the session, set the state to playing
+ // and resume playback.
+ playbackState.add(playbackState.value.copyWith(
+ controls: [MediaControl.pause, MediaControl.stop],
+ processingState: AudioProcessingState.ready,
+ playing: true,
+ ));
+ if (_completer == null) {
+ run();
+ } else {
+ _sleeper.interrupt();
+ }
+ }
+ }
+
+ @override
+ Future<void> pause() async {
+ _interrupted = false;
+ playbackState.add(playbackState.value.copyWith(
+ controls: [MediaControl.play, MediaControl.stop],
+ processingState: AudioProcessingState.ready,
+ playing: false,
+ ));
+ _signal();
+ }
+
+ @override
+ Future<void> stop() async {
+ playbackState.add(playbackState.value.copyWith(
+ controls: [],
+ processingState: AudioProcessingState.idle,
+ playing: false,
+ ));
+ _running = false;
+ _signal();
+ // Wait for the speech to stop
+ await _completer?.future;
+ // Shut down this task
+ await super.stop();
+ }
+
+ void _signal() {
+ _sleeper.interrupt();
+ _tts.interrupt();
+ }
+}
+
+/// An object that performs interruptable sleep.
+class Sleeper {
+ Completer<void>? _blockingCompleter;
+
+ /// Sleep for a duration. If sleep is interrupted, a
+ /// [SleeperInterruptedException] will be thrown.
+ Future<void> sleep([Duration? duration]) async {
+ _blockingCompleter = Completer();
+ if (duration != null) {
+ await Future.any<void>(
+ [Future.delayed(duration), _blockingCompleter!.future]);
+ } else {
+ await _blockingCompleter!.future;
+ }
+ final interrupted = _blockingCompleter!.isCompleted;
+ _blockingCompleter = null;
+ if (interrupted) {
+ throw SleeperInterruptedException();
+ }
+ }
+
+ /// Interrupt any sleep that's underway.
+ void interrupt() {
+ if (_blockingCompleter?.isCompleted == false) {
+ _blockingCompleter!.complete();
+ }
+ }
+}
+
+class SleeperInterruptedException {}
+
+/// A wrapper around FlutterTts that makes it easier to wait for speech to
+/// complete.
+class Tts {
+ final FlutterTts _flutterTts = FlutterTts();
+ Completer<void>? _speechCompleter;
+ bool _interruptRequested = false;
+ bool _playing = false;
+
+ Tts() {
+ _flutterTts.setCompletionHandler(() {
+ _speechCompleter?.complete();
+ });
+ }
+
+ bool get playing => _playing;
+
+ Future<void> speak(String text) async {
+ _playing = true;
+ if (!_interruptRequested) {
+ _speechCompleter = Completer();
+ await _flutterTts.speak(text);
+ await _speechCompleter!.future;
+ _speechCompleter = null;
+ }
+ _playing = false;
+ if (_interruptRequested) {
+ _interruptRequested = false;
+ throw TtsInterruptedException();
+ }
+ }
+
+ Future<void> stop() async {
+ if (_playing) {
+ await _flutterTts.stop();
+ _speechCompleter?.complete();
+ }
+ }
+
+ void interrupt() {
+ if (_playing) {
+ _interruptRequested = true;
+ stop();
+ }
+ }
+}
+
+class TtsInterruptedException {}
diff --git a/packages/audio_service/example/lib/example_playlist.dart b/packages/audio_service/example/lib/example_playlist.dart
new file mode 100644
index 00000000..29ad4498
--- /dev/null
+++ b/packages/audio_service/example/lib/example_playlist.dart
@@ -0,0 +1,693 @@
+// ignore_for_file: public_member_api_docs
+
+// This example demonstrates a playlist with repeat/shuffle functionality.
+//
+// To run this example, use:
+//
+// flutter run -t lib/example_playlist.dart
+
+import 'dart:async';
+
+import 'package:audio_service/audio_service.dart';
+import 'package:audio_service_example/common.dart';
+import 'package:audio_session/audio_session.dart';
+import 'package:flutter/material.dart';
+import 'package:just_audio/just_audio.dart';
+import 'package:rxdart/rxdart.dart';
+
+// You might want to provide this using dependency injection rather than a
+// global variable.
+late AudioPlayerHandler _audioHandler;
+
+Future<void> main() async {
+ _audioHandler = await AudioService.init(
+ builder: () => AudioPlayerHandlerImpl(),
+ config: const AudioServiceConfig(
+ androidNotificationChannelId: 'com.ryanheise.myapp.channel.audio',
+ androidNotificationChannelName: 'Audio playback',
+ androidNotificationOngoing: true,
+ ),
+ );
+ runApp(const MyApp());
+}
+
+/// The app widget
+class MyApp extends StatelessWidget {
+ const MyApp({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ return MaterialApp(
+ title: 'Audio Service Demo',
+ theme: ThemeData(primarySwatch: Colors.blue),
+ home: const MainScreen(),
+ );
+ }
+}
+
+/// The main screen.
+class MainScreen extends StatelessWidget {
+ const MainScreen({super.key});
+
+ Stream<Duration> get _bufferedPositionStream => _audioHandler.playbackState
+ .map((state) => state.bufferedPosition)
+ .distinct();
+ Stream<Duration?> get _durationStream =>
+ _audioHandler.mediaItem.map((item) => item?.duration).distinct();
+ Stream<PositionData> get _positionDataStream =>
+ Rx.combineLatest3<Duration, Duration, Duration?, PositionData>(
+ AudioService.position,
+ _bufferedPositionStream,
+ _durationStream,
+ (position, bufferedPosition, duration) => PositionData(
+ position, bufferedPosition, duration ?? Duration.zero));
+
+ @override
+ Widget build(BuildContext context) {
+ return Scaffold(
+ body: SafeArea(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.center,
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ // MediaItem display
+ Expanded(
+ child: StreamBuilder<MediaItem?>(
+ stream: _audioHandler.mediaItem,
+ builder: (context, snapshot) {
+ final mediaItem = snapshot.data;
+ if (mediaItem == null) return const SizedBox();
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.center,
+ children: [
+ if (mediaItem.artUri != null)
+ Expanded(
+ child: Padding(
+ padding: const EdgeInsets.all(8.0),
+ child: Center(
+ child: Image.network('${mediaItem.artUri!}'),
+ ),
+ ),
+ ),
+ Text(mediaItem.album ?? '',
+ style: Theme.of(context).textTheme.titleLarge),
+ Text(mediaItem.title),
+ ],
+ );
+ },
+ ),
+ ),
+ // Playback controls
+ ControlButtons(_audioHandler),
+ // A seek bar.
+ StreamBuilder<PositionData>(
+ stream: _positionDataStream,
+ builder: (context, snapshot) {
+ final positionData = snapshot.data ??
+ PositionData(Duration.zero, Duration.zero, Duration.zero);
+ return SeekBar(
+ duration: positionData.duration,
+ position: positionData.position,
+ onChangeEnd: (newPosition) {
+ _audioHandler.seek(newPosition);
+ },
+ );
+ },
+ ),
+ const SizedBox(height: 8.0),
+ // Repeat/shuffle controls
+ Row(
+ children: [
+ StreamBuilder<AudioServiceRepeatMode>(
+ stream: _audioHandler.playbackState
+ .map((state) => state.repeatMode)
+ .distinct(),
+ builder: (context, snapshot) {
+ final repeatMode =
+ snapshot.data ?? AudioServiceRepeatMode.none;
+ const icons = [
+ Icon(Icons.repeat, color: Colors.grey),
+ Icon(Icons.repeat, color: Colors.orange),
+ Icon(Icons.repeat_one, color: Colors.orange),
+ ];
+ const cycleModes = [
+ AudioServiceRepeatMode.none,
+ AudioServiceRepeatMode.all,
+ AudioServiceRepeatMode.one,
+ ];
+ final index = cycleModes.indexOf(repeatMode);
+ return IconButton(
+ icon: icons[index],
+ onPressed: () {
+ _audioHandler.setRepeatMode(cycleModes[
+ (cycleModes.indexOf(repeatMode) + 1) %
+ cycleModes.length]);
+ },
+ );
+ },
+ ),
+ Expanded(
+ child: Text(
+ "Playlist",
+ style: Theme.of(context).textTheme.titleLarge,
+ textAlign: TextAlign.center,
+ ),
+ ),
+ StreamBuilder<bool>(
+ stream: _audioHandler.playbackState
+ .map((state) =>
+ state.shuffleMode == AudioServiceShuffleMode.all)
+ .distinct(),
+ builder: (context, snapshot) {
+ final shuffleModeEnabled = snapshot.data ?? false;
+ return IconButton(
+ icon: shuffleModeEnabled
+ ? const Icon(Icons.shuffle, color: Colors.orange)
+ : const Icon(Icons.shuffle, color: Colors.grey),
+ onPressed: () async {
+ final enable = !shuffleModeEnabled;
+ await _audioHandler.setShuffleMode(enable
+ ? AudioServiceShuffleMode.all
+ : AudioServiceShuffleMode.none);
+ },
+ );
+ },
+ ),
+ ],
+ ),
+ // Playlist
+ SizedBox(
+ height: 240.0,
+ child: StreamBuilder<QueueState>(
+ stream: _audioHandler.queueState,
+ builder: (context, snapshot) {
+ final queueState = snapshot.data ?? QueueState.empty;
+ final queue = queueState.queue;
+ return ReorderableListView(
+ onReorder: (int oldIndex, int newIndex) {
+ if (oldIndex < newIndex) newIndex--;
+ _audioHandler.moveQueueItem(oldIndex, newIndex);
+ },
+ children: [
+ for (var i = 0; i < queue.length; i++)
+ Dismissible(
+ key: ValueKey(queue[i].id),
+ background: Container(
+ color: Colors.redAccent,
+ alignment: Alignment.centerRight,
+ child: const Padding(
+ padding: EdgeInsets.only(right: 8.0),
+ child: Icon(Icons.delete, color: Colors.white),
+ ),
+ ),
+ onDismissed: (dismissDirection) {
+ _audioHandler.removeQueueItemAt(i);
+ },
+ child: Material(
+ color: i == queueState.queueIndex
+ ? Colors.grey.shade300
+ : null,
+ child: ListTile(
+ title: Text(queue[i].title),
+ onTap: () => _audioHandler.skipToQueueItem(i),
+ ),
+ ),
+ ),
+ ],
+ );
+ },
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+class ControlButtons extends StatelessWidget {
+ final AudioPlayerHandler audioHandler;
+
+ const ControlButtons(this.audioHandler, {super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ return Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ IconButton(
+ icon: const Icon(Icons.volume_up),
+ onPressed: () {
+ showSliderDialog(
+ context: context,
+ title: "Adjust volume",
+ divisions: 10,
+ min: 0.0,
+ max: 1.0,
+ value: audioHandler.volume.value,
+ stream: audioHandler.volume,
+ onChanged: audioHandler.setVolume,
+ );
+ },
+ ),
+ StreamBuilder<QueueState>(
+ stream: audioHandler.queueState,
+ builder: (context, snapshot) {
+ final queueState = snapshot.data ?? QueueState.empty;
+ return IconButton(
+ icon: const Icon(Icons.skip_previous),
+ onPressed:
+ queueState.hasPrevious ? audioHandler.skipToPrevious : null,
+ );
+ },
+ ),
+ StreamBuilder<PlaybackState>(
+ stream: audioHandler.playbackState,
+ builder: (context, snapshot) {
+ final playbackState = snapshot.data;
+ final processingState = playbackState?.processingState;
+ final playing = playbackState?.playing;
+ if (processingState == AudioProcessingState.loading ||
+ processingState == AudioProcessingState.buffering) {
+ return Container(
+ margin: const EdgeInsets.all(8.0),
+ width: 64.0,
+ height: 64.0,
+ child: const CircularProgressIndicator(),
+ );
+ } else if (playing != true) {
+ return IconButton(
+ icon: const Icon(Icons.play_arrow),
+ iconSize: 64.0,
+ onPressed: audioHandler.play,
+ );
+ } else {
+ return IconButton(
+ icon: const Icon(Icons.pause),
+ iconSize: 64.0,
+ onPressed: audioHandler.pause,
+ );
+ }
+ },
+ ),
+ StreamBuilder<QueueState>(
+ stream: audioHandler.queueState,
+ builder: (context, snapshot) {
+ final queueState = snapshot.data ?? QueueState.empty;
+ return IconButton(
+ icon: const Icon(Icons.skip_next),
+ onPressed: queueState.hasNext ? audioHandler.skipToNext : null,
+ );
+ },
+ ),
+ StreamBuilder<double>(
+ stream: audioHandler.speed,
+ builder: (context, snapshot) => IconButton(
+ icon: Text("${snapshot.data?.toStringAsFixed(1)}x",
+ style: const TextStyle(fontWeight: FontWeight.bold)),
+ onPressed: () {
+ showSliderDialog(
+ context: context,
+ title: "Adjust speed",
+ divisions: 10,
+ min: 0.5,
+ max: 1.5,
+ value: audioHandler.speed.value,
+ stream: audioHandler.speed,
+ onChanged: audioHandler.setSpeed,
+ );
+ },
+ ),
+ ),
+ ],
+ );
+ }
+}
+
+class QueueState {
+ static const QueueState empty =
+ QueueState([], 0, [], AudioServiceRepeatMode.none);
+
+ final List<MediaItem> queue;
+ final int? queueIndex;
+ final List<int>? shuffleIndices;
+ final AudioServiceRepeatMode repeatMode;
+
+ const QueueState(
+ this.queue, this.queueIndex, this.shuffleIndices, this.repeatMode);
+
+ bool get hasPrevious =>
+ repeatMode != AudioServiceRepeatMode.none || (queueIndex ?? 0) > 0;
+ bool get hasNext =>
+ repeatMode != AudioServiceRepeatMode.none ||
+ (queueIndex ?? 0) + 1 < queue.length;
+
+ List<int> get indices =>
+ shuffleIndices ?? List.generate(queue.length, (i) => i);
+}
+
+/// An [AudioHandler] for playing a list of podcast episodes.
+///
+/// This class exposes the interface and not the implementation.
+abstract class AudioPlayerHandler implements AudioHandler {
+ Stream<QueueState> get queueState;
+ Future<void> moveQueueItem(int currentIndex, int newIndex);
+ ValueStream<double> get volume;
+ Future<void> setVolume(double volume);
+ ValueStream<double> get speed;
+}
+
+/// The implementation of [AudioPlayerHandler].
+///
+/// This handler is backed by a just_audio player. The player's effective
+/// sequence is mapped onto the handler's queue, and the player's state is
+/// mapped onto the handler's state.
+class AudioPlayerHandlerImpl extends BaseAudioHandler
+ with SeekHandler
+ implements AudioPlayerHandler {
+ // ignore: close_sinks
+ final BehaviorSubject<List<MediaItem>> _recentSubject =
+ BehaviorSubject.seeded(<MediaItem>[]);
+ final _mediaLibrary = MediaLibrary();
+ final _player = AudioPlayer();
+ final _playlist = ConcatenatingAudioSource(children: []);
+ @override
+ final BehaviorSubject<double> volume = BehaviorSubject.seeded(1.0);
+ @override
+ final BehaviorSubject<double> speed = BehaviorSubject.seeded(1.0);
+ final _mediaItemExpando = Expando<MediaItem>();
+
+ /// A stream of the current effective sequence from just_audio.
+ Stream<List<IndexedAudioSource>> get _effectiveSequence => Rx.combineLatest3<
+ List<IndexedAudioSource>?,
+ List<int>?,
+ bool,
+ List<IndexedAudioSource>?>(_player.sequenceStream,
+ _player.shuffleIndicesStream, _player.shuffleModeEnabledStream,
+ (sequence, shuffleIndices, shuffleModeEnabled) {
+ if (sequence == null) return [];
+ if (!shuffleModeEnabled) return sequence;
+ if (shuffleIndices == null) return null;
+ if (shuffleIndices.length != sequence.length) return null;
+ return shuffleIndices.map((i) => sequence[i]).toList();
+ }).whereType<List<IndexedAudioSource>>();
+
+ /// Computes the effective queue index taking shuffle mode into account.
+ int? getQueueIndex(
+ int? currentIndex, bool shuffleModeEnabled, List<int>? shuffleIndices) {
+ final effectiveIndices = _player.effectiveIndices ?? [];
+ final shuffleIndicesInv = List.filled(effectiveIndices.length, 0);
+ for (var i = 0; i < effectiveIndices.length; i++) {
+ shuffleIndicesInv[effectiveIndices[i]] = i;
+ }
+ return (shuffleModeEnabled &&
+ ((currentIndex ?? 0) < shuffleIndicesInv.length))
+ ? shuffleIndicesInv[currentIndex ?? 0]
+ : currentIndex;
+ }
+
+ /// A stream reporting the combined state of the current queue and the current
+ /// media item within that queue.
+ @override
+ Stream<QueueState> get queueState =>
+ Rx.combineLatest3<List<MediaItem>, PlaybackState, List<int>, QueueState>(
+ queue,
+ playbackState,
+ _player.shuffleIndicesStream.whereType<List<int>>(),
+ (queue, playbackState, shuffleIndices) => QueueState(
+ queue,
+ playbackState.queueIndex,
+ playbackState.shuffleMode == AudioServiceShuffleMode.all
+ ? shuffleIndices
+ : null,
+ playbackState.repeatMode,
+ )).where((state) =>
+ state.shuffleIndices == null ||
+ state.queue.length == state.shuffleIndices!.length);
+
+ @override
+ Future<void> setShuffleMode(AudioServiceShuffleMode shuffleMode) async {
+ final enabled = shuffleMode == AudioServiceShuffleMode.all;
+ if (enabled) {
+ await _player.shuffle();
+ }
+ playbackState.add(playbackState.value.copyWith(shuffleMode: shuffleMode));
+ await _player.setShuffleModeEnabled(enabled);
+ }
+
+ @override
+ Future<void> setRepeatMode(AudioServiceRepeatMode repeatMode) async {
+ playbackState.add(playbackState.value.copyWith(repeatMode: repeatMode));
+ await _player.setLoopMode(LoopMode.values[repeatMode.index]);
+ }
+
+ @override
+ Future<void> setSpeed(double speed) async {
+ this.speed.add(speed);
+ await _player.setSpeed(speed);
+ }
+
+ @override
+ Future<void> setVolume(double volume) async {
+ this.volume.add(volume);
+ await _player.setVolume(volume);
+ }
+
+ AudioPlayerHandlerImpl() {
+ _init();
+ }
+
+ Future<void> _init() async {
+ final session = await AudioSession.instance;
+ await session.configure(const AudioSessionConfiguration.speech());
+ // Broadcast speed changes. Debounce so that we don't flood the notification
+ // with updates.
+ speed.debounceTime(const Duration(milliseconds: 250)).listen((speed) {
+ playbackState.add(playbackState.value.copyWith(speed: speed));
+ });
+ // Load and broadcast the initial queue
+ await updateQueue(_mediaLibrary.items[MediaLibrary.albumsRootId]!);
+ // For Android 11, record the most recent item so it can be resumed.
+ mediaItem
+ .whereType<MediaItem>()
+ .listen((item) => _recentSubject.add([item]));
+ // Broadcast media item changes.
+ Rx.combineLatest4<int?, List<MediaItem>, bool, List<int>?, MediaItem?>(
+ _player.currentIndexStream,
+ queue,
+ _player.shuffleModeEnabledStream,
+ _player.shuffleIndicesStream,
+ (index, queue, shuffleModeEnabled, shuffleIndices) {
+ final queueIndex =
+ getQueueIndex(index, shuffleModeEnabled, shuffleIndices);
+ return (queueIndex != null && queueIndex < queue.length)
+ ? queue[queueIndex]
+ : null;
+ }).whereType<MediaItem>().distinct().listen(mediaItem.add);
+ // Propagate all events from the audio player to AudioService clients.
+ _player.playbackEventStream.listen(_broadcastState);
+ _player.shuffleModeEnabledStream
+ .listen((enabled) => _broadcastState(_player.playbackEvent));
+ // In this example, the service stops when reaching the end.
+ _player.processingStateStream.listen((state) {
+ if (state == ProcessingState.completed) {
+ stop();
+ _player.seek(Duration.zero, index: 0);
+ }
+ });
+ // Broadcast the current queue.
+ _effectiveSequence
+ .map((sequence) =>
+ sequence.map((source) => _mediaItemExpando[source]!).toList())
+ .pipe(queue);
+ // Load the playlist.
+ _playlist.addAll(queue.value.map(_itemToSource).toList());
+ await _player.setAudioSource(_playlist);
+ }
+
+ AudioSource _itemToSource(MediaItem mediaItem) {
+ final audioSource = AudioSource.uri(Uri.parse(mediaItem.id));
+ _mediaItemExpando[audioSource] = mediaItem;
+ return audioSource;
+ }
+
+ List<AudioSource> _itemsToSources(List<MediaItem> mediaItems) =>
+ mediaItems.map(_itemToSource).toList();
+
+ @override
+ Future<List<MediaItem>> getChildren(String parentMediaId,
+ [Map<String, dynamic>? options]) async {
+ switch (parentMediaId) {
+ case AudioService.recentRootId:
+ // When the user resumes a media session, tell the system what the most
+ // recently played item was.
+ return _recentSubject.value;
+ default:
+ // Allow client to browse the media library.
+ return _mediaLibrary.items[parentMediaId]!;
+ }
+ }
+
+ @override
+ ValueStream<Map<String, dynamic>> subscribeToChildren(String parentMediaId) {
+ switch (parentMediaId) {
+ case AudioService.recentRootId:
+ final stream = _recentSubject.map((_) => <String, dynamic>{});
+ return _recentSubject.hasValue
+ ? stream.shareValueSeeded(<String, dynamic>{})
+ : stream.shareValue();
+ default:
+ return Stream.value(_mediaLibrary.items[parentMediaId])
+ .map((_) => <String, dynamic>{})
+ .shareValue();
+ }
+ }
+
+ @override
+ Future<void> addQueueItem(MediaItem mediaItem) async {
+ await _playlist.add(_itemToSource(mediaItem));
+ }
+
+ @override
+ Future<void> addQueueItems(List<MediaItem> mediaItems) async {
+ await _playlist.addAll(_itemsToSources(mediaItems));
+ }
+
+ @override
+ Future<void> insertQueueItem(int index, MediaItem mediaItem) async {
+ await _playlist.insert(index, _itemToSource(mediaItem));
+ }
+
+ @override
+ Future<void> updateQueue(List<MediaItem> queue) async {
+ await _playlist.clear();
+ await _playlist.addAll(_itemsToSources(queue));
+ }
+
+ @override
+ Future<void> updateMediaItem(MediaItem mediaItem) async {
+ final index = queue.value.indexWhere((item) => item.id == mediaItem.id);
+ _mediaItemExpando[_player.sequence![index]] = mediaItem;
+ }
+
+ @override
+ Future<void> removeQueueItem(MediaItem mediaItem) async {
+ final index = queue.value.indexOf(mediaItem);
+ await _playlist.removeAt(index);
+ }
+
+ @override
+ Future<void> moveQueueItem(int currentIndex, int newIndex) async {
+ await _playlist.move(currentIndex, newIndex);
+ }
+
+ @override
+ Future<void> skipToNext() => _player.seekToNext();
+
+ @override
+ Future<void> skipToPrevious() => _player.seekToPrevious();
+
+ @override
+ Future<void> skipToQueueItem(int index) async {
+ if (index < 0 || index >= _playlist.children.length) return;
+ // This jumps to the beginning of the queue item at [index].
+ _player.seek(Duration.zero,
+ index: _player.shuffleModeEnabled
+ ? _player.shuffleIndices![index]
+ : index);
+ }
+
+ @override
+ Future<void> play() => _player.play();
+
+ @override
+ Future<void> pause() => _player.pause();
+
+ @override
+ Future<void> seek(Duration position) => _player.seek(position);
+
+ @override
+ Future<void> stop() async {
+ await _player.stop();
+ await playbackState.firstWhere(
+ (state) => state.processingState == AudioProcessingState.idle);
+ }
+
+ /// Broadcasts the current state to all clients.
+ void _broadcastState(PlaybackEvent event) {
+ final playing = _player.playing;
+ final queueIndex = getQueueIndex(
+ event.currentIndex, _player.shuffleModeEnabled, _player.shuffleIndices);
+ playbackState.add(playbackState.value.copyWith(
+ controls: [
+ MediaControl.skipToPrevious,
+ if (playing) MediaControl.pause else MediaControl.play,
+ MediaControl.stop,
+ MediaControl.skipToNext,
+ ],
+ systemActions: const {
+ MediaAction.seek,
+ MediaAction.seekForward,
+ MediaAction.seekBackward,
+ },
+ androidCompactActionIndices: const [0, 1, 3],
+ processingState: const {
+ ProcessingState.idle: AudioProcessingState.idle,
+ ProcessingState.loading: AudioProcessingState.loading,
+ ProcessingState.buffering: AudioProcessingState.buffering,
+ ProcessingState.ready: AudioProcessingState.ready,
+ ProcessingState.completed: AudioProcessingState.completed,
+ }[_player.processingState]!,
+ playing: playing,
+ updatePosition: _player.position,
+ bufferedPosition: _player.bufferedPosition,
+ speed: _player.speed,
+ queueIndex: queueIndex,
+ ));
+ }
+}
+
+/// Provides access to a library of media items. In your app, this could come
+/// from a database or web service.
+class MediaLibrary {
+ static const albumsRootId = 'albums';
+
+ final items = <String, List<MediaItem>>{
+ AudioService.browsableRootId: const [
+ MediaItem(
+ id: albumsRootId,
+ title: "Albums",
+ playable: false,
+ ),
+ ],
+ albumsRootId: [
+ MediaItem(
+ id: 'https://s3.amazonaws.com/scifri-episodes/scifri20181123-episode.mp3',
+ album: "Science Friday",
+ title: "A Salute To Head-Scratching Science",
+ artist: "Science Friday and WNYC Studios",
+ duration: const Duration(milliseconds: 5739820),
+ artUri: Uri.parse(
+ 'https://media.wnyc.org/i/1400/1400/l/80/1/ScienceFriday_WNYCStudios_1400.jpg'),
+ ),
+ MediaItem(
+ id: 'https://s3.amazonaws.com/scifri-segments/scifri201711241.mp3',
+ album: "Science Friday",
+ title: "From Cat Rheology To Operatic Incompetence",
+ artist: "Science Friday and WNYC Studios",
+ duration: const Duration(milliseconds: 2856950),
+ artUri: Uri.parse(
+ 'https://media.wnyc.org/i/1400/1400/l/80/1/ScienceFriday_WNYCStudios_1400.jpg'),
+ ),
+ MediaItem(
+ id: 'https://s3.amazonaws.com/scifri-segments/scifri202011274.mp3',
+ album: "Science Friday",
+ title: "Laugh Along At Home With The Ig Nobel Awards",
+ artist: "Science Friday and WNYC Studios",
+ duration: const Duration(milliseconds: 1791883),
+ artUri: Uri.parse(
+ 'https://media.wnyc.org/i/1400/1400/l/80/1/ScienceFriday_WNYCStudios_1400.jpg'),
+ ),
+ ],
+ };
+}
diff --git a/packages/audio_service/example/lib/main.dart b/packages/audio_service/example/lib/main.dart
new file mode 100644
index 00000000..e415c978
--- /dev/null
+++ b/packages/audio_service/example/lib/main.dart
@@ -0,0 +1,232 @@
+// ignore_for_file: public_member_api_docs
+
+// FOR MORE EXAMPLES, VISIT THE GITHUB REPOSITORY AT:
+//
+// https://github.com/ryanheise/audio_service
+//
+// This example implements a minimal audio handler that renders the current
+// media item and playback state to the system notification and responds to 4
+// media actions:
+//
+// - play
+// - pause
+// - seek
+// - stop
+//
+// To run this example, use:
+//
+// flutter run
+
+import 'dart:async';
+
+import 'package:audio_service/audio_service.dart';
+import 'package:audio_service_example/common.dart';
+import 'package:flutter/foundation.dart';
+import 'package:flutter/material.dart';
+import 'package:just_audio/just_audio.dart';
+import 'package:rxdart/rxdart.dart';
+
+// You might want to provide this using dependency injection rather than a
+// global variable.
+late AudioHandler _audioHandler;
+
+Future<void> main() async {
+ _audioHandler = await AudioService.init(
+ builder: () => AudioPlayerHandler(),
+ config: const AudioServiceConfig(
+ androidNotificationChannelId: 'com.ryanheise.myapp.channel.audio',
+ androidNotificationChannelName: 'Audio playback',
+ androidNotificationOngoing: true,
+ ),
+ );
+ runApp(const MyApp());
+}
+
+class MyApp extends StatelessWidget {
+ const MyApp({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ return MaterialApp(
+ title: 'Audio Service Demo',
+ theme: ThemeData(primarySwatch: Colors.blue),
+ home: const MainScreen(),
+ );
+ }
+}
+
+class MainScreen extends StatelessWidget {
+ const MainScreen({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ return Scaffold(
+ appBar: AppBar(
+ title: const Text('Audio Service Demo'),
+ ),
+ body: Center(
+ child: Column(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ // Show media item title
+ StreamBuilder<MediaItem?>(
+ stream: _audioHandler.mediaItem,
+ builder: (context, snapshot) {
+ final mediaItem = snapshot.data;
+ return Text(mediaItem?.title ?? '');
+ },
+ ),
+ // Play/pause/stop buttons.
+ StreamBuilder<bool>(
+ stream: _audioHandler.playbackState
+ .map((state) => state.playing)
+ .distinct(),
+ builder: (context, snapshot) {
+ final playing = snapshot.data ?? false;
+ return Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ _button(Icons.fast_rewind, _audioHandler.rewind),
+ if (playing)
+ _button(Icons.pause, _audioHandler.pause)
+ else
+ _button(Icons.play_arrow, _audioHandler.play),
+ _button(Icons.stop, _audioHandler.stop),
+ _button(Icons.fast_forward, _audioHandler.fastForward),
+ ],
+ );
+ },
+ ),
+ // A seek bar.
+ StreamBuilder<MediaState>(
+ stream: _mediaStateStream,
+ builder: (context, snapshot) {
+ final mediaState = snapshot.data;
+ return SeekBar(
+ duration: mediaState?.mediaItem?.duration ?? Duration.zero,
+ position: mediaState?.position ?? Duration.zero,
+ onChangeEnd: (newPosition) {
+ _audioHandler.seek(newPosition);
+ },
+ );
+ },
+ ),
+ // Display the processing state.
+ StreamBuilder<AudioProcessingState>(
+ stream: _audioHandler.playbackState
+ .map((state) => state.processingState)
+ .distinct(),
+ builder: (context, snapshot) {
+ final processingState =
+ snapshot.data ?? AudioProcessingState.idle;
+ return Text(
+ // ignore: deprecated_member_use
+ "Processing state: ${describeEnum(processingState)}");
+ },
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ /// A stream reporting the combined state of the current media item and its
+ /// current position.
+ Stream<MediaState> get _mediaStateStream =>
+ Rx.combineLatest2<MediaItem?, Duration, MediaState>(
+ _audioHandler.mediaItem,
+ AudioService.position,
+ (mediaItem, position) => MediaState(mediaItem, position));
+
+ IconButton _button(IconData iconData, VoidCallback onPressed) => IconButton(
+ icon: Icon(iconData),
+ iconSize: 64.0,
+ onPressed: onPressed,
+ );
+}
+
+class MediaState {
+ final MediaItem? mediaItem;
+ final Duration position;
+
+ MediaState(this.mediaItem, this.position);
+}
+
+/// An [AudioHandler] for playing a single item.
+class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
+ static final _item = MediaItem(
+ id: 'https://s3.amazonaws.com/scifri-episodes/scifri20181123-episode.mp3',
+ album: "Science Friday",
+ title: "A Salute To Head-Scratching Science",
+ artist: "Science Friday and WNYC Studios",
+ duration: const Duration(milliseconds: 5739820),
+ artUri: Uri.parse(
+ 'https://media.wnyc.org/i/1400/1400/l/80/1/ScienceFriday_WNYCStudios_1400.jpg'),
+ );
+
+ final _player = AudioPlayer();
+
+ /// Initialise our audio handler.
+ AudioPlayerHandler() {
+ // So that our clients (the Flutter UI and the system notification) know
+ // what state to display, here we set up our audio handler to broadcast all
+ // playback state changes as they happen via playbackState...
+ _player.playbackEventStream.map(_transformEvent).pipe(playbackState);
+ // ... and also the current media item via mediaItem.
+ mediaItem.add(_item);
+
+ // Load the player.
+ _player.setAudioSource(AudioSource.uri(Uri.parse(_item.id)));
+ }
+
+ // In this simple example, we handle only 4 actions: play, pause, seek and
+ // stop. Any button press from the Flutter UI, notification, lock screen or
+ // headset will be routed through to these 4 methods so that you can handle
+ // your audio playback logic in one place.
+
+ @override
+ Future<void> play() => _player.play();
+
+ @override
+ Future<void> pause() => _player.pause();
+
+ @override
+ Future<void> seek(Duration position) => _player.seek(position);
+
+ @override
+ Future<void> stop() => _player.stop();
+
+ /// Transform a just_audio event into an audio_service state.
+ ///
+ /// This method is used from the constructor. Every event received from the
+ /// just_audio player will be transformed into an audio_service state so that
+ /// it can be broadcast to audio_service clients.
+ PlaybackState _transformEvent(PlaybackEvent event) {
+ return PlaybackState(
+ controls: [
+ MediaControl.rewind,
+ if (_player.playing) MediaControl.pause else MediaControl.play,
+ MediaControl.stop,
+ MediaControl.fastForward,
+ ],
+ systemActions: const {
+ MediaAction.seek,
+ MediaAction.seekForward,
+ MediaAction.seekBackward,
+ },
+ androidCompactActionIndices: const [0, 1, 3],
+ processingState: const {
+ ProcessingState.idle: AudioProcessingState.idle,
+ ProcessingState.loading: AudioProcessingState.loading,
+ ProcessingState.buffering: AudioProcessingState.buffering,
+ ProcessingState.ready: AudioProcessingState.ready,
+ ProcessingState.completed: AudioProcessingState.completed,
+ }[_player.processingState]!,
+ playing: _player.playing,
+ updatePosition: _player.position,
+ bufferedPosition: _player.bufferedPosition,
+ speed: _player.speed,
+ queueIndex: event.currentIndex,
+ );
+ }
+}
diff --git a/packages/audio_service/example/macos/Flutter/Flutter-Debug.xcconfig b/packages/audio_service/example/macos/Flutter/Flutter-Debug.xcconfig
new file mode 100644
index 00000000..785633d3
--- /dev/null
+++ b/packages/audio_service/example/macos/Flutter/Flutter-Debug.xcconfig
@@ -0,0 +1,2 @@
+#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"
+#include "ephemeral/Flutter-Generated.xcconfig"
diff --git a/packages/audio_service/example/macos/Flutter/Flutter-Release.xcconfig b/packages/audio_service/example/macos/Flutter/Flutter-Release.xcconfig
new file mode 100644
index 00000000..5fba960c
--- /dev/null
+++ b/packages/audio_service/example/macos/Flutter/Flutter-Release.xcconfig
@@ -0,0 +1,2 @@
+#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"
+#include "ephemeral/Flutter-Generated.xcconfig"
diff --git a/packages/audio_service/example/macos/Podfile b/packages/audio_service/example/macos/Podfile
new file mode 100644
index 00000000..9ec46f8c
--- /dev/null
+++ b/packages/audio_service/example/macos/Podfile
@@ -0,0 +1,40 @@
+platform :osx, '10.15'
+
+# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
+ENV['COCOAPODS_DISABLE_STATS'] = 'true'
+
+project 'Runner', {
+ 'Debug' => :debug,
+ 'Profile' => :release,
+ 'Release' => :release,
+}
+
+def flutter_root
+ generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'ephemeral', 'Flutter-Generated.xcconfig'), __FILE__)
+ unless File.exist?(generated_xcode_build_settings_path)
+ raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure \"flutter pub get\" is executed first"
+ end
+
+ File.foreach(generated_xcode_build_settings_path) do |line|
+ matches = line.match(/FLUTTER_ROOT\=(.*)/)
+ return matches[1].strip if matches
+ end
+ raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Flutter-Generated.xcconfig, then run \"flutter pub get\""
+end
+
+require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)
+
+flutter_macos_podfile_setup
+
+target 'Runner' do
+ use_frameworks!
+ use_modular_headers!
+
+ flutter_install_all_macos_pods File.dirname(File.realpath(__FILE__))
+end
+
+post_install do |installer|
+ installer.pods_project.targets.each do |target|
+ flutter_additional_macos_build_settings(target)
+ end
+end
diff --git a/packages/audio_service/example/macos/Podfile.lock b/packages/audio_service/example/macos/Podfile.lock
new file mode 100644
index 00000000..781f6dd7
--- /dev/null
+++ b/packages/audio_service/example/macos/Podfile.lock
@@ -0,0 +1,49 @@
+PODS:
+ - device_info_plus (0.0.1):
+ - FlutterMacOS
+ - flutter_tts (0.0.1):
+ - FlutterMacOS
+ - FlutterMacOS (1.0.0)
+ - FMDB (2.7.5):
+ - FMDB/standard (= 2.7.5)
+ - FMDB/standard (2.7.5)
+ - path_provider_macos (0.0.1):
+ - FlutterMacOS
+ - sqflite (0.0.2):
+ - FlutterMacOS
+ - FMDB (>= 2.7.5)
+
+DEPENDENCIES:
+ - device_info_plus (from `Flutter/ephemeral/.symlinks/plugins/device_info_plus/macos`)
+ - flutter_tts (from `Flutter/ephemeral/.symlinks/plugins/flutter_tts/macos`)
+ - FlutterMacOS (from `Flutter/ephemeral`)
+ - path_provider_macos (from `Flutter/ephemeral/.symlinks/plugins/path_provider_macos/macos`)
+ - sqflite (from `Flutter/ephemeral/.symlinks/plugins/sqflite/macos`)
+
+SPEC REPOS:
+ trunk:
+ - FMDB
+
+EXTERNAL SOURCES:
+ device_info_plus:
+ :path: Flutter/ephemeral/.symlinks/plugins/device_info_plus/macos
+ flutter_tts:
+ :path: Flutter/ephemeral/.symlinks/plugins/flutter_tts/macos
+ FlutterMacOS:
+ :path: Flutter/ephemeral
+ path_provider_macos:
+ :path: Flutter/ephemeral/.symlinks/plugins/path_provider_macos/macos
+ sqflite:
+ :path: Flutter/ephemeral/.symlinks/plugins/sqflite/macos
+
+SPEC CHECKSUMS:
+ device_info_plus: 5401765fde0b8d062a2f8eb65510fb17e77cf07f
+ flutter_tts: 64651204e5d276ffea5a910f942d5e9785a96085
+ FlutterMacOS: 8f6f14fa908a6fb3fba0cd85dbd81ec4b251fb24
+ FMDB: 2ce00b547f966261cd18927a3ddb07cb6f3db82a
+ path_provider_macos: 160cab0d5461f0c0e02995469a98f24bdb9a3f1f
+ sqflite: a5789cceda41d54d23f31d6de539d65bb14100ea
+
+PODFILE CHECKSUM: 0d3963a09fc94f580682bd88480486da345dc3f0
+
+COCOAPODS: 1.15.2
diff --git a/packages/audio_service/example/macos/Runner.xcodeproj/project.pbxproj b/packages/audio_service/example/macos/Runner.xcodeproj/project.pbxproj
new file mode 100644
index 00000000..a996b5a9
--- /dev/null
+++ b/packages/audio_service/example/macos/Runner.xcodeproj/project.pbxproj
@@ -0,0 +1,678 @@
+// !$*UTF8*$!
+{
+ archiveVersion = 1;
+ classes = {
+ };
+ objectVersion = 54;
+ objects = {
+
+/* Begin PBXAggregateTarget section */
+ 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = {
+ isa = PBXAggregateTarget;
+ buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */;
+ buildPhases = (
+ 33CC111E2044C6BF0003C045 /* ShellScript */,
+ );
+ dependencies = (
+ );
+ name = "Flutter Assemble";
+ productName = FLX;
+ };
+/* End PBXAggregateTarget section */
+
+/* Begin PBXBuildFile section */
+ 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; };
+ 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; };
+ 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; };
+ 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; };
+ 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; };
+ 694FF95961DABE91D34A0C9C /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 804DE6D45226FDAC0CD200F6 /* Pods_Runner.framework */; };
+ 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; };
+/* End PBXBuildFile section */
+
+/* Begin PBXContainerItemProxy section */
+ 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = {
+ isa = PBXContainerItemProxy;
+ containerPortal = 33CC10E52044A3C60003C045 /* Project object */;
+ proxyType = 1;
+ remoteGlobalIDString = 33CC111A2044C6BA0003C045;
+ remoteInfo = FLX;
+ };
+/* End PBXContainerItemProxy section */
+
+/* Begin PBXCopyFilesBuildPhase section */
+ 33CC110E2044A8840003C045 /* Bundle Framework */ = {
+ isa = PBXCopyFilesBuildPhase;
+ buildActionMask = 2147483647;
+ dstPath = "";
+ dstSubfolderSpec = 10;
+ files = (
+ );
+ name = "Bundle Framework";
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+/* End PBXCopyFilesBuildPhase section */
+
+/* Begin PBXFileReference section */
+ 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = "<group>"; };
+ 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = "<group>"; };
+ 33CC10ED2044A3C60003C045 /* example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = example.app; sourceTree = BUILT_PRODUCTS_DIR; };
+ 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
+ 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = "<group>"; };
+ 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = "<group>"; };
+ 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = "<group>"; };
+ 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = "<group>"; };
+ 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = "<group>"; };
+ 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = "<group>"; };
+ 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = "<group>"; };
+ 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = "<group>"; };
+ 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = "<group>"; };
+ 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = "<group>"; };
+ 4FAED060E2079955DDCE79BA /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = "<group>"; };
+ 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = "<group>"; };
+ 804DE6D45226FDAC0CD200F6 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; };
+ 895ED93C3491726793B453C4 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = "<group>"; };
+ 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = "<group>"; };
+ 9F03299CBC64584E7B7A00B3 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = "<group>"; };
+/* End PBXFileReference section */
+
+/* Begin PBXFrameworksBuildPhase section */
+ 33CC10EA2044A3C60003C045 /* Frameworks */ = {
+ isa = PBXFrameworksBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */,
+ 694FF95961DABE91D34A0C9C /* Pods_Runner.framework in Frameworks */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+/* End PBXFrameworksBuildPhase section */
+
+/* Begin PBXGroup section */
+ 33BA886A226E78AF003329D5 /* Configs */ = {
+ isa = PBXGroup;
+ children = (
+ 33E5194F232828860026EE4D /* AppInfo.xcconfig */,
+ 9740EEB21CF90195004384FC /* Debug.xcconfig */,
+ 7AFA3C8E1D35360C0083082E /* Release.xcconfig */,
+ 333000ED22D3DE5D00554162 /* Warnings.xcconfig */,
+ );
+ path = Configs;
+ sourceTree = "<group>";
+ };
+ 33CC10E42044A3C60003C045 = {
+ isa = PBXGroup;
+ children = (
+ 33FAB671232836740065AC1E /* Runner */,
+ 33CEB47122A05771004F2AC0 /* Flutter */,
+ 33CC10EE2044A3C60003C045 /* Products */,
+ D73912EC22F37F3D000D13A0 /* Frameworks */,
+ CA2D0CABE6615C8B34ECDF56 /* Pods */,
+ );
+ sourceTree = "<group>";
+ };
+ 33CC10EE2044A3C60003C045 /* Products */ = {
+ isa = PBXGroup;
+ children = (
+ 33CC10ED2044A3C60003C045 /* example.app */,
+ );
+ name = Products;
+ sourceTree = "<group>";
+ };
+ 33CC11242044D66E0003C045 /* Resources */ = {
+ isa = PBXGroup;
+ children = (
+ 33CC10F22044A3C60003C045 /* Assets.xcassets */,
+ 33CC10F42044A3C60003C045 /* MainMenu.xib */,
+ 33CC10F72044A3C60003C045 /* Info.plist */,
+ );
+ name = Resources;
+ path = ..;
+ sourceTree = "<group>";
+ };
+ 33CEB47122A05771004F2AC0 /* Flutter */ = {
+ isa = PBXGroup;
+ children = (
+ 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */,
+ 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */,
+ 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */,
+ 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */,
+ );
+ path = Flutter;
+ sourceTree = "<group>";
+ };
+ 33FAB671232836740065AC1E /* Runner */ = {
+ isa = PBXGroup;
+ children = (
+ 33CC10F02044A3C60003C045 /* AppDelegate.swift */,
+ 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */,
+ 33E51913231747F40026EE4D /* DebugProfile.entitlements */,
+ 33E51914231749380026EE4D /* Release.entitlements */,
+ 33CC11242044D66E0003C045 /* Resources */,
+ 33BA886A226E78AF003329D5 /* Configs */,
+ );
+ path = Runner;
+ sourceTree = "<group>";
+ };
+ CA2D0CABE6615C8B34ECDF56 /* Pods */ = {
+ isa = PBXGroup;
+ children = (
+ 9F03299CBC64584E7B7A00B3 /* Pods-Runner.debug.xcconfig */,
+ 895ED93C3491726793B453C4 /* Pods-Runner.release.xcconfig */,
+ 4FAED060E2079955DDCE79BA /* Pods-Runner.profile.xcconfig */,
+ );
+ path = Pods;
+ sourceTree = "<group>";
+ };
+ D73912EC22F37F3D000D13A0 /* Frameworks */ = {
+ isa = PBXGroup;
+ children = (
+ 804DE6D45226FDAC0CD200F6 /* Pods_Runner.framework */,
+ );
+ name = Frameworks;
+ sourceTree = "<group>";
+ };
+/* End PBXGroup section */
+
+/* Begin PBXNativeTarget section */
+ 33CC10EC2044A3C60003C045 /* Runner */ = {
+ isa = PBXNativeTarget;
+ buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */;
+ buildPhases = (
+ 0C7E4A8569B8969DDCC672C9 /* [CP] Check Pods Manifest.lock */,
+ 33CC10E92044A3C60003C045 /* Sources */,
+ 33CC10EA2044A3C60003C045 /* Frameworks */,
+ 33CC10EB2044A3C60003C045 /* Resources */,
+ 33CC110E2044A8840003C045 /* Bundle Framework */,
+ 3399D490228B24CF009A79C7 /* ShellScript */,
+ 2FFC5189B543BBDC406BFFD9 /* [CP] Embed Pods Frameworks */,
+ );
+ buildRules = (
+ );
+ dependencies = (
+ 33CC11202044C79F0003C045 /* PBXTargetDependency */,
+ );
+ name = Runner;
+ packageProductDependencies = (
+ 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */,
+ );
+ productName = Runner;
+ productReference = 33CC10ED2044A3C60003C045 /* example.app */;
+ productType = "com.apple.product-type.application";
+ };
+/* End PBXNativeTarget section */
+
+/* Begin PBXProject section */
+ 33CC10E52044A3C60003C045 /* Project object */ = {
+ isa = PBXProject;
+ attributes = {
+ LastSwiftUpdateCheck = 0920;
+ LastUpgradeCheck = 1510;
+ ORGANIZATIONNAME = "The Flutter Authors";
+ TargetAttributes = {
+ 33CC10EC2044A3C60003C045 = {
+ CreatedOnToolsVersion = 9.2;
+ LastSwiftMigration = 1100;
+ ProvisioningStyle = Automatic;
+ SystemCapabilities = {
+ com.apple.Sandbox = {
+ enabled = 1;
+ };
+ };
+ };
+ 33CC111A2044C6BA0003C045 = {
+ CreatedOnToolsVersion = 9.2;
+ ProvisioningStyle = Manual;
+ };
+ };
+ };
+ buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */;
+ compatibilityVersion = "Xcode 8.0";
+ developmentRegion = en;
+ hasScannedForEncodings = 0;
+ knownRegions = (
+ en,
+ Base,
+ );
+ mainGroup = 33CC10E42044A3C60003C045;
+ packageReferences = (
+ 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "FlutterGeneratedPluginSwiftPackage" */,
+ );
+ productRefGroup = 33CC10EE2044A3C60003C045 /* Products */;
+ projectDirPath = "";
+ projectRoot = "";
+ targets = (
+ 33CC10EC2044A3C60003C045 /* Runner */,
+ 33CC111A2044C6BA0003C045 /* Flutter Assemble */,
+ );
+ };
+/* End PBXProject section */
+
+/* Begin PBXResourcesBuildPhase section */
+ 33CC10EB2044A3C60003C045 /* Resources */ = {
+ isa = PBXResourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */,
+ 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+/* End PBXResourcesBuildPhase section */
+
+/* Begin PBXShellScriptBuildPhase section */
+ 0C7E4A8569B8969DDCC672C9 /* [CP] Check Pods Manifest.lock */ = {
+ isa = PBXShellScriptBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ );
+ inputFileListPaths = (
+ );
+ inputPaths = (
+ "${PODS_PODFILE_DIR_PATH}/Podfile.lock",
+ "${PODS_ROOT}/Manifest.lock",
+ );
+ name = "[CP] Check Pods Manifest.lock";
+ outputFileListPaths = (
+ );
+ outputPaths = (
+ "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt",
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ shellPath = /bin/sh;
+ shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
+ showEnvVarsInLog = 0;
+ };
+ 2FFC5189B543BBDC406BFFD9 /* [CP] Embed Pods Frameworks */ = {
+ isa = PBXShellScriptBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ );
+ inputPaths = (
+ "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh",
+ "${BUILT_PRODUCTS_DIR}/FMDB/FMDB.framework",
+ "${BUILT_PRODUCTS_DIR}/device_info_plus/device_info_plus.framework",
+ "${BUILT_PRODUCTS_DIR}/flutter_tts/flutter_tts.framework",
+ "${BUILT_PRODUCTS_DIR}/path_provider_macos/path_provider_macos.framework",
+ "${BUILT_PRODUCTS_DIR}/sqflite/sqflite.framework",
+ );
+ name = "[CP] Embed Pods Frameworks";
+ outputPaths = (
+ "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/FMDB.framework",
+ "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/device_info_plus.framework",
+ "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/flutter_tts.framework",
+ "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/path_provider_macos.framework",
+ "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/sqflite.framework",
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ shellPath = /bin/sh;
+ shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n";
+ showEnvVarsInLog = 0;
+ };
+ 3399D490228B24CF009A79C7 /* ShellScript */ = {
+ isa = PBXShellScriptBuildPhase;
+ alwaysOutOfDate = 1;
+ buildActionMask = 2147483647;
+ files = (
+ );
+ inputFileListPaths = (
+ );
+ inputPaths = (
+ );
+ outputFileListPaths = (
+ );
+ outputPaths = (
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ shellPath = /bin/sh;
+ shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n";
+ };
+ 33CC111E2044C6BF0003C045 /* ShellScript */ = {
+ isa = PBXShellScriptBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ );
+ inputFileListPaths = (
+ Flutter/ephemeral/FlutterInputs.xcfilelist,
+ );
+ inputPaths = (
+ Flutter/ephemeral/tripwire,
+ );
+ outputFileListPaths = (
+ Flutter/ephemeral/FlutterOutputs.xcfilelist,
+ );
+ outputPaths = (
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ shellPath = /bin/sh;
+ shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire";
+ };
+/* End PBXShellScriptBuildPhase section */
+
+/* Begin PBXSourcesBuildPhase section */
+ 33CC10E92044A3C60003C045 /* Sources */ = {
+ isa = PBXSourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */,
+ 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */,
+ 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+/* End PBXSourcesBuildPhase section */
+
+/* Begin PBXTargetDependency section */
+ 33CC11202044C79F0003C045 /* PBXTargetDependency */ = {
+ isa = PBXTargetDependency;
+ target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */;
+ targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */;
+ };
+/* End PBXTargetDependency section */
+
+/* Begin PBXVariantGroup section */
+ 33CC10F42044A3C60003C045 /* MainMenu.xib */ = {
+ isa = PBXVariantGroup;
+ children = (
+ 33CC10F52044A3C60003C045 /* Base */,
+ );
+ name = MainMenu.xib;
+ path = Runner;
+ sourceTree = "<group>";
+ };
+/* End PBXVariantGroup section */
+
+/* Begin XCBuildConfiguration section */
+ 338D0CE9231458BD00FA5F75 /* Profile */ = {
+ isa = XCBuildConfiguration;
+ baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
+ buildSettings = {
+ ALWAYS_SEARCH_USER_PATHS = NO;
+ CLANG_ANALYZER_NONNULL = YES;
+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
+ CLANG_CXX_LIBRARY = "libc++";
+ CLANG_ENABLE_MODULES = YES;
+ CLANG_ENABLE_OBJC_ARC = YES;
+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
+ CLANG_WARN_BOOL_CONVERSION = YES;
+ CLANG_WARN_CONSTANT_CONVERSION = YES;
+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
+ CLANG_WARN_EMPTY_BODY = YES;
+ CLANG_WARN_ENUM_CONVERSION = YES;
+ CLANG_WARN_INFINITE_RECURSION = YES;
+ CLANG_WARN_INT_CONVERSION = YES;
+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
+ CLANG_WARN_SUSPICIOUS_MOVE = YES;
+ CODE_SIGN_IDENTITY = "-";
+ COPY_PHASE_STRIP = NO;
+ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+ ENABLE_NS_ASSERTIONS = NO;
+ ENABLE_STRICT_OBJC_MSGSEND = YES;
+ GCC_C_LANGUAGE_STANDARD = gnu11;
+ GCC_NO_COMMON_BLOCKS = YES;
+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
+ GCC_WARN_UNUSED_FUNCTION = YES;
+ GCC_WARN_UNUSED_VARIABLE = YES;
+ MACOSX_DEPLOYMENT_TARGET = 10.14;
+ MTL_ENABLE_DEBUG_INFO = NO;
+ SDKROOT = macosx;
+ SWIFT_COMPILATION_MODE = wholemodule;
+ SWIFT_OPTIMIZATION_LEVEL = "-O";
+ };
+ name = Profile;
+ };
+ 338D0CEA231458BD00FA5F75 /* Profile */ = {
+ isa = XCBuildConfiguration;
+ baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */;
+ buildSettings = {
+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+ CLANG_ENABLE_MODULES = YES;
+ CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements;
+ CODE_SIGN_STYLE = Automatic;
+ COMBINE_HIDPI_IMAGES = YES;
+ FRAMEWORK_SEARCH_PATHS = (
+ "$(inherited)",
+ "$(PROJECT_DIR)/Flutter/ephemeral",
+ );
+ INFOPLIST_FILE = Runner/Info.plist;
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@executable_path/../Frameworks",
+ );
+ MACOSX_DEPLOYMENT_TARGET = 10.15;
+ PROVISIONING_PROFILE_SPECIFIER = "";
+ SWIFT_VERSION = 5.0;
+ };
+ name = Profile;
+ };
+ 338D0CEB231458BD00FA5F75 /* Profile */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ CODE_SIGN_STYLE = Manual;
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ };
+ name = Profile;
+ };
+ 33CC10F92044A3C60003C045 /* Debug */ = {
+ isa = XCBuildConfiguration;
+ baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */;
+ buildSettings = {
+ ALWAYS_SEARCH_USER_PATHS = NO;
+ CLANG_ANALYZER_NONNULL = YES;
+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
+ CLANG_CXX_LIBRARY = "libc++";
+ CLANG_ENABLE_MODULES = YES;
+ CLANG_ENABLE_OBJC_ARC = YES;
+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
+ CLANG_WARN_BOOL_CONVERSION = YES;
+ CLANG_WARN_CONSTANT_CONVERSION = YES;
+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
+ CLANG_WARN_EMPTY_BODY = YES;
+ CLANG_WARN_ENUM_CONVERSION = YES;
+ CLANG_WARN_INFINITE_RECURSION = YES;
+ CLANG_WARN_INT_CONVERSION = YES;
+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
+ CLANG_WARN_SUSPICIOUS_MOVE = YES;
+ CODE_SIGN_IDENTITY = "-";
+ COPY_PHASE_STRIP = NO;
+ DEBUG_INFORMATION_FORMAT = dwarf;
+ ENABLE_STRICT_OBJC_MSGSEND = YES;
+ ENABLE_TESTABILITY = YES;
+ GCC_C_LANGUAGE_STANDARD = gnu11;
+ GCC_DYNAMIC_NO_PIC = NO;
+ GCC_NO_COMMON_BLOCKS = YES;
+ GCC_OPTIMIZATION_LEVEL = 0;
+ GCC_PREPROCESSOR_DEFINITIONS = (
+ "DEBUG=1",
+ "$(inherited)",
+ );
+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
+ GCC_WARN_UNUSED_FUNCTION = YES;
+ GCC_WARN_UNUSED_VARIABLE = YES;
+ MACOSX_DEPLOYMENT_TARGET = 10.14;
+ MTL_ENABLE_DEBUG_INFO = YES;
+ ONLY_ACTIVE_ARCH = YES;
+ SDKROOT = macosx;
+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
+ SWIFT_OPTIMIZATION_LEVEL = "-Onone";
+ };
+ name = Debug;
+ };
+ 33CC10FA2044A3C60003C045 /* Release */ = {
+ isa = XCBuildConfiguration;
+ baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
+ buildSettings = {
+ ALWAYS_SEARCH_USER_PATHS = NO;
+ CLANG_ANALYZER_NONNULL = YES;
+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
+ CLANG_CXX_LIBRARY = "libc++";
+ CLANG_ENABLE_MODULES = YES;
+ CLANG_ENABLE_OBJC_ARC = YES;
+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
+ CLANG_WARN_BOOL_CONVERSION = YES;
+ CLANG_WARN_CONSTANT_CONVERSION = YES;
+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
+ CLANG_WARN_EMPTY_BODY = YES;
+ CLANG_WARN_ENUM_CONVERSION = YES;
+ CLANG_WARN_INFINITE_RECURSION = YES;
+ CLANG_WARN_INT_CONVERSION = YES;
+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
+ CLANG_WARN_SUSPICIOUS_MOVE = YES;
+ CODE_SIGN_IDENTITY = "-";
+ COPY_PHASE_STRIP = NO;
+ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+ ENABLE_NS_ASSERTIONS = NO;
+ ENABLE_STRICT_OBJC_MSGSEND = YES;
+ GCC_C_LANGUAGE_STANDARD = gnu11;
+ GCC_NO_COMMON_BLOCKS = YES;
+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
+ GCC_WARN_UNUSED_FUNCTION = YES;
+ GCC_WARN_UNUSED_VARIABLE = YES;
+ MACOSX_DEPLOYMENT_TARGET = 10.14;
+ MTL_ENABLE_DEBUG_INFO = NO;
+ SDKROOT = macosx;
+ SWIFT_COMPILATION_MODE = wholemodule;
+ SWIFT_OPTIMIZATION_LEVEL = "-O";
+ };
+ name = Release;
+ };
+ 33CC10FC2044A3C60003C045 /* Debug */ = {
+ isa = XCBuildConfiguration;
+ baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */;
+ buildSettings = {
+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+ CLANG_ENABLE_MODULES = YES;
+ CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements;
+ CODE_SIGN_STYLE = Automatic;
+ COMBINE_HIDPI_IMAGES = YES;
+ FRAMEWORK_SEARCH_PATHS = (
+ "$(inherited)",
+ "$(PROJECT_DIR)/Flutter/ephemeral",
+ );
+ INFOPLIST_FILE = Runner/Info.plist;
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@executable_path/../Frameworks",
+ );
+ MACOSX_DEPLOYMENT_TARGET = 10.15;
+ PROVISIONING_PROFILE_SPECIFIER = "";
+ SWIFT_OPTIMIZATION_LEVEL = "-Onone";
+ SWIFT_VERSION = 5.0;
+ };
+ name = Debug;
+ };
+ 33CC10FD2044A3C60003C045 /* Release */ = {
+ isa = XCBuildConfiguration;
+ baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */;
+ buildSettings = {
+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+ CLANG_ENABLE_MODULES = YES;
+ CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements;
+ CODE_SIGN_STYLE = Automatic;
+ COMBINE_HIDPI_IMAGES = YES;
+ FRAMEWORK_SEARCH_PATHS = (
+ "$(inherited)",
+ "$(PROJECT_DIR)/Flutter/ephemeral",
+ );
+ INFOPLIST_FILE = Runner/Info.plist;
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@executable_path/../Frameworks",
+ );
+ MACOSX_DEPLOYMENT_TARGET = 10.15;
+ PROVISIONING_PROFILE_SPECIFIER = "";
+ SWIFT_VERSION = 5.0;
+ };
+ name = Release;
+ };
+ 33CC111C2044C6BA0003C045 /* Debug */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ CODE_SIGN_STYLE = Manual;
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ };
+ name = Debug;
+ };
+ 33CC111D2044C6BA0003C045 /* Release */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ CODE_SIGN_STYLE = Automatic;
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ };
+ name = Release;
+ };
+/* End XCBuildConfiguration section */
+
+/* Begin XCConfigurationList section */
+ 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ 33CC10F92044A3C60003C045 /* Debug */,
+ 33CC10FA2044A3C60003C045 /* Release */,
+ 338D0CE9231458BD00FA5F75 /* Profile */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Release;
+ };
+ 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ 33CC10FC2044A3C60003C045 /* Debug */,
+ 33CC10FD2044A3C60003C045 /* Release */,
+ 338D0CEA231458BD00FA5F75 /* Profile */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Release;
+ };
+ 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ 33CC111C2044C6BA0003C045 /* Debug */,
+ 33CC111D2044C6BA0003C045 /* Release */,
+ 338D0CEB231458BD00FA5F75 /* Profile */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Release;
+ };
+/* End XCConfigurationList section */
+
+/* Begin XCLocalSwiftPackageReference section */
+ 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "FlutterGeneratedPluginSwiftPackage" */ = {
+ isa = XCLocalSwiftPackageReference;
+ relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage;
+ };
+/* End XCLocalSwiftPackageReference section */
+
+/* Begin XCSwiftPackageProductDependency section */
+ 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = {
+ isa = XCSwiftPackageProductDependency;
+ productName = FlutterGeneratedPluginSwiftPackage;
+ };
+/* End XCSwiftPackageProductDependency section */
+ };
+ rootObject = 33CC10E52044A3C60003C045 /* Project object */;
+}
diff --git a/packages/audio_service/example/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/packages/audio_service/example/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
new file mode 100644
index 00000000..18d98100
--- /dev/null
+++ b/packages/audio_service/example/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>IDEDidComputeMac32BitWarning</key>
+ <true/>
+</dict>
+</plist>
diff --git a/packages/audio_service/example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/packages/audio_service/example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme
new file mode 100644
index 00000000..8de585b4
--- /dev/null
+++ b/packages/audio_service/example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme
@@ -0,0 +1,119 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Scheme
+ LastUpgradeVersion = "1510"
+ version = "1.3">
+ <BuildAction
+ parallelizeBuildables = "YES"
+ buildImplicitDependencies = "YES">
+ <PreActions>
+ <ExecutionAction
+ ActionType = "Xcode.IDEStandardExecutionActionsCore.ExecutionActionType.ShellScriptAction">
+ <ActionContent
+ title = "Run Prepare Flutter Framework Script"
+ scriptText = "&quot;$FLUTTER_ROOT&quot;/packages/flutter_tools/bin/macos_assemble.sh prepare&#10;">
+ <EnvironmentBuildable>
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "33CC10EC2044A3C60003C045"
+ BuildableName = "example.app"
+ BlueprintName = "Runner"
+ ReferencedContainer = "container:Runner.xcodeproj">
+ </BuildableReference>
+ </EnvironmentBuildable>
+ </ActionContent>
+ </ExecutionAction>
+ </PreActions>
+ <BuildActionEntries>
+ <BuildActionEntry
+ buildForTesting = "YES"
+ buildForRunning = "YES"
+ buildForProfiling = "YES"
+ buildForArchiving = "YES"
+ buildForAnalyzing = "YES">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "33CC10EC2044A3C60003C045"
+ BuildableName = "example.app"
+ BlueprintName = "Runner"
+ ReferencedContainer = "container:Runner.xcodeproj">
+ </BuildableReference>
+ </BuildActionEntry>
+ </BuildActionEntries>
+ </BuildAction>
+ <TestAction
+ buildConfiguration = "Debug"
+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+ shouldUseLaunchSchemeArgsEnv = "YES">
+ <Testables>
+ <TestableReference
+ skipped = "NO">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "00380F9121DF178D00097171"
+ BuildableName = "RunnerUITests.xctest"
+ BlueprintName = "RunnerUITests"
+ ReferencedContainer = "container:Runner.xcodeproj">
+ </BuildableReference>
+ </TestableReference>
+ </Testables>
+ <MacroExpansion>
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "33CC10EC2044A3C60003C045"
+ BuildableName = "example.app"
+ BlueprintName = "Runner"
+ ReferencedContainer = "container:Runner.xcodeproj">
+ </BuildableReference>
+ </MacroExpansion>
+ <AdditionalOptions>
+ </AdditionalOptions>
+ </TestAction>
+ <LaunchAction
+ buildConfiguration = "Debug"
+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+ launchStyle = "0"
+ useCustomWorkingDirectory = "NO"
+ ignoresPersistentStateOnLaunch = "NO"
+ debugDocumentVersioning = "YES"
+ debugServiceExtension = "internal"
+ allowLocationSimulation = "YES">
+ <BuildableProductRunnable
+ runnableDebuggingMode = "0">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "33CC10EC2044A3C60003C045"
+ BuildableName = "example.app"
+ BlueprintName = "Runner"
+ ReferencedContainer = "container:Runner.xcodeproj">
+ </BuildableReference>
+ </BuildableProductRunnable>
+ <AdditionalOptions>
+ </AdditionalOptions>
+ </LaunchAction>
+ <ProfileAction
+ buildConfiguration = "Release"
+ shouldUseLaunchSchemeArgsEnv = "YES"
+ savedToolIdentifier = ""
+ useCustomWorkingDirectory = "NO"
+ debugDocumentVersioning = "YES">
+ <BuildableProductRunnable
+ runnableDebuggingMode = "0">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "33CC10EC2044A3C60003C045"
+ BuildableName = "example.app"
+ BlueprintName = "Runner"
+ ReferencedContainer = "container:Runner.xcodeproj">
+ </BuildableReference>
+ </BuildableProductRunnable>
+ </ProfileAction>
+ <AnalyzeAction
+ buildConfiguration = "Debug">
+ </AnalyzeAction>
+ <ArchiveAction
+ buildConfiguration = "Release"
+ revealArchiveInOrganizer = "YES">
+ </ArchiveAction>
+</Scheme>
diff --git a/packages/audio_service/example/macos/Runner.xcworkspace/contents.xcworkspacedata b/packages/audio_service/example/macos/Runner.xcworkspace/contents.xcworkspacedata
new file mode 100644
index 00000000..21a3cc14
--- /dev/null
+++ b/packages/audio_service/example/macos/Runner.xcworkspace/contents.xcworkspacedata
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Workspace
+ version = "1.0">
+ <FileRef
+ location = "group:Runner.xcodeproj">
+ </FileRef>
+ <FileRef
+ location = "group:Pods/Pods.xcodeproj">
+ </FileRef>
+</Workspace>
diff --git a/packages/audio_service/example/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/packages/audio_service/example/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
new file mode 100644
index 00000000..18d98100
--- /dev/null
+++ b/packages/audio_service/example/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>IDEDidComputeMac32BitWarning</key>
+ <true/>
+</dict>
+</plist>
diff --git a/packages/audio_service/example/macos/Runner/AppDelegate.swift b/packages/audio_service/example/macos/Runner/AppDelegate.swift
new file mode 100644
index 00000000..b3c17614
--- /dev/null
+++ b/packages/audio_service/example/macos/Runner/AppDelegate.swift
@@ -0,0 +1,13 @@
+import Cocoa
+import FlutterMacOS
+
+@main
+class AppDelegate: FlutterAppDelegate {
+ override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
+ return true
+ }
+
+ override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
+ return true
+ }
+}
diff --git a/packages/audio_service/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/packages/audio_service/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json
new file mode 100644
index 00000000..a2ec33f1
--- /dev/null
+++ b/packages/audio_service/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json
@@ -0,0 +1,68 @@
+{
+ "images" : [
+ {
+ "size" : "16x16",
+ "idiom" : "mac",
+ "filename" : "app_icon_16.png",
+ "scale" : "1x"
+ },
+ {
+ "size" : "16x16",
+ "idiom" : "mac",
+ "filename" : "app_icon_32.png",
+ "scale" : "2x"
+ },
+ {
+ "size" : "32x32",
+ "idiom" : "mac",
+ "filename" : "app_icon_32.png",
+ "scale" : "1x"
+ },
+ {
+ "size" : "32x32",
+ "idiom" : "mac",
+ "filename" : "app_icon_64.png",
+ "scale" : "2x"
+ },
+ {
+ "size" : "128x128",
+ "idiom" : "mac",
+ "filename" : "app_icon_128.png",
+ "scale" : "1x"
+ },
+ {
+ "size" : "128x128",
+ "idiom" : "mac",
+ "filename" : "app_icon_256.png",
+ "scale" : "2x"
+ },
+ {
+ "size" : "256x256",
+ "idiom" : "mac",
+ "filename" : "app_icon_256.png",
+ "scale" : "1x"
+ },
+ {
+ "size" : "256x256",
+ "idiom" : "mac",
+ "filename" : "app_icon_512.png",
+ "scale" : "2x"
+ },
+ {
+ "size" : "512x512",
+ "idiom" : "mac",
+ "filename" : "app_icon_512.png",
+ "scale" : "1x"
+ },
+ {
+ "size" : "512x512",
+ "idiom" : "mac",
+ "filename" : "app_icon_1024.png",
+ "scale" : "2x"
+ }
+ ],
+ "info" : {
+ "version" : 1,
+ "author" : "xcode"
+ }
+}
diff --git a/packages/audio_service/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/packages/audio_service/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png
new file mode 100644
index 00000000..3c4935a7
Binary files /dev/null and b/packages/audio_service/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ
diff --git a/packages/audio_service/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/packages/audio_service/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png
new file mode 100644
index 00000000..ed4cc164
Binary files /dev/null and b/packages/audio_service/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ
diff --git a/packages/audio_service/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/packages/audio_service/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png
new file mode 100644
index 00000000..483be613
Binary files /dev/null and b/packages/audio_service/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ
diff --git a/packages/audio_service/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/packages/audio_service/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png
new file mode 100644
index 00000000..bcbf36df
Binary files /dev/null and b/packages/audio_service/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ
diff --git a/packages/audio_service/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/packages/audio_service/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png
new file mode 100644
index 00000000..9c0a6528
Binary files /dev/null and b/packages/audio_service/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ
diff --git a/packages/audio_service/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/packages/audio_service/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png
new file mode 100644
index 00000000..e71a7261
Binary files /dev/null and b/packages/audio_service/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ
diff --git a/packages/audio_service/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/packages/audio_service/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png
new file mode 100644
index 00000000..8a31fe2d
Binary files /dev/null and b/packages/audio_service/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ
diff --git a/packages/audio_service/example/macos/Runner/Base.lproj/MainMenu.xib b/packages/audio_service/example/macos/Runner/Base.lproj/MainMenu.xib
new file mode 100644
index 00000000..537341ab
--- /dev/null
+++ b/packages/audio_service/example/macos/Runner/Base.lproj/MainMenu.xib
@@ -0,0 +1,339 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="14490.70" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
+ <dependencies>
+ <deployment identifier="macosx"/>
+ <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="14490.70"/>
+ <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
+ </dependencies>
+ <objects>
+ <customObject id="-2" userLabel="File's Owner" customClass="NSApplication">
+ <connections>
+ <outlet property="delegate" destination="Voe-Tx-rLC" id="GzC-gU-4Uq"/>
+ </connections>
+ </customObject>
+ <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>
+ <customObject id="-3" userLabel="Application" customClass="NSObject"/>
+ <customObject id="Voe-Tx-rLC" customClass="AppDelegate" customModule="Runner" customModuleProvider="target">
+ <connections>
+ <outlet property="applicationMenu" destination="uQy-DD-JDr" id="XBo-yE-nKs"/>
+ <outlet property="mainFlutterWindow" destination="QvC-M9-y7g" id="gIp-Ho-8D9"/>
+ </connections>
+ </customObject>
+ <customObject id="YLy-65-1bz" customClass="NSFontManager"/>
+ <menu title="Main Menu" systemMenu="main" id="AYu-sK-qS6">
+ <items>
+ <menuItem title="APP_NAME" id="1Xt-HY-uBw">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <menu key="submenu" title="APP_NAME" systemMenu="apple" id="uQy-DD-JDr">
+ <items>
+ <menuItem title="About APP_NAME" id="5kV-Vb-QxS">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <connections>
+ <action selector="orderFrontStandardAboutPanel:" target="-1" id="Exp-CZ-Vem"/>
+ </connections>
+ </menuItem>
+ <menuItem isSeparatorItem="YES" id="VOq-y0-SEH"/>
+ <menuItem title="Preferences…" keyEquivalent="," id="BOF-NM-1cW"/>
+ <menuItem isSeparatorItem="YES" id="wFC-TO-SCJ"/>
+ <menuItem title="Services" id="NMo-om-nkz">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <menu key="submenu" title="Services" systemMenu="services" id="hz9-B4-Xy5"/>
+ </menuItem>
+ <menuItem isSeparatorItem="YES" id="4je-JR-u6R"/>
+ <menuItem title="Hide APP_NAME" keyEquivalent="h" id="Olw-nP-bQN">
+ <connections>
+ <action selector="hide:" target="-1" id="PnN-Uc-m68"/>
+ </connections>
+ </menuItem>
+ <menuItem title="Hide Others" keyEquivalent="h" id="Vdr-fp-XzO">
+ <modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
+ <connections>
+ <action selector="hideOtherApplications:" target="-1" id="VT4-aY-XCT"/>
+ </connections>
+ </menuItem>
+ <menuItem title="Show All" id="Kd2-mp-pUS">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <connections>
+ <action selector="unhideAllApplications:" target="-1" id="Dhg-Le-xox"/>
+ </connections>
+ </menuItem>
+ <menuItem isSeparatorItem="YES" id="kCx-OE-vgT"/>
+ <menuItem title="Quit APP_NAME" keyEquivalent="q" id="4sb-4s-VLi">
+ <connections>
+ <action selector="terminate:" target="-1" id="Te7-pn-YzF"/>
+ </connections>
+ </menuItem>
+ </items>
+ </menu>
+ </menuItem>
+ <menuItem title="Edit" id="5QF-Oa-p0T">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <menu key="submenu" title="Edit" id="W48-6f-4Dl">
+ <items>
+ <menuItem title="Undo" keyEquivalent="z" id="dRJ-4n-Yzg">
+ <connections>
+ <action selector="undo:" target="-1" id="M6e-cu-g7V"/>
+ </connections>
+ </menuItem>
+ <menuItem title="Redo" keyEquivalent="Z" id="6dh-zS-Vam">
+ <connections>
+ <action selector="redo:" target="-1" id="oIA-Rs-6OD"/>
+ </connections>
+ </menuItem>
+ <menuItem isSeparatorItem="YES" id="WRV-NI-Exz"/>
+ <menuItem title="Cut" keyEquivalent="x" id="uRl-iY-unG">
+ <connections>
+ <action selector="cut:" target="-1" id="YJe-68-I9s"/>
+ </connections>
+ </menuItem>
+ <menuItem title="Copy" keyEquivalent="c" id="x3v-GG-iWU">
+ <connections>
+ <action selector="copy:" target="-1" id="G1f-GL-Joy"/>
+ </connections>
+ </menuItem>
+ <menuItem title="Paste" keyEquivalent="v" id="gVA-U4-sdL">
+ <connections>
+ <action selector="paste:" target="-1" id="UvS-8e-Qdg"/>
+ </connections>
+ </menuItem>
+ <menuItem title="Paste and Match Style" keyEquivalent="V" id="WeT-3V-zwk">
+ <modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
+ <connections>
+ <action selector="pasteAsPlainText:" target="-1" id="cEh-KX-wJQ"/>
+ </connections>
+ </menuItem>
+ <menuItem title="Delete" id="pa3-QI-u2k">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <connections>
+ <action selector="delete:" target="-1" id="0Mk-Ml-PaM"/>
+ </connections>
+ </menuItem>
+ <menuItem title="Select All" keyEquivalent="a" id="Ruw-6m-B2m">
+ <connections>
+ <action selector="selectAll:" target="-1" id="VNm-Mi-diN"/>
+ </connections>
+ </menuItem>
+ <menuItem isSeparatorItem="YES" id="uyl-h8-XO2"/>
+ <menuItem title="Find" id="4EN-yA-p0u">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <menu key="submenu" title="Find" id="1b7-l0-nxx">
+ <items>
+ <menuItem title="Find…" tag="1" keyEquivalent="f" id="Xz5-n4-O0W">
+ <connections>
+ <action selector="performFindPanelAction:" target="-1" id="cD7-Qs-BN4"/>
+ </connections>
+ </menuItem>
+ <menuItem title="Find and Replace…" tag="12" keyEquivalent="f" id="YEy-JH-Tfz">
+ <modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
+ <connections>
+ <action selector="performFindPanelAction:" target="-1" id="WD3-Gg-5AJ"/>
+ </connections>
+ </menuItem>
+ <menuItem title="Find Next" tag="2" keyEquivalent="g" id="q09-fT-Sye">
+ <connections>
+ <action selector="performFindPanelAction:" target="-1" id="NDo-RZ-v9R"/>
+ </connections>
+ </menuItem>
+ <menuItem title="Find Previous" tag="3" keyEquivalent="G" id="OwM-mh-QMV">
+ <connections>
+ <action selector="performFindPanelAction:" target="-1" id="HOh-sY-3ay"/>
+ </connections>
+ </menuItem>
+ <menuItem title="Use Selection for Find" tag="7" keyEquivalent="e" id="buJ-ug-pKt">
+ <connections>
+ <action selector="performFindPanelAction:" target="-1" id="U76-nv-p5D"/>
+ </connections>
+ </menuItem>
+ <menuItem title="Jump to Selection" keyEquivalent="j" id="S0p-oC-mLd">
+ <connections>
+ <action selector="centerSelectionInVisibleArea:" target="-1" id="IOG-6D-g5B"/>
+ </connections>
+ </menuItem>
+ </items>
+ </menu>
+ </menuItem>
+ <menuItem title="Spelling and Grammar" id="Dv1-io-Yv7">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <menu key="submenu" title="Spelling" id="3IN-sU-3Bg">
+ <items>
+ <menuItem title="Show Spelling and Grammar" keyEquivalent=":" id="HFo-cy-zxI">
+ <connections>
+ <action selector="showGuessPanel:" target="-1" id="vFj-Ks-hy3"/>
+ </connections>
+ </menuItem>
+ <menuItem title="Check Document Now" keyEquivalent=";" id="hz2-CU-CR7">
+ <connections>
+ <action selector="checkSpelling:" target="-1" id="fz7-VC-reM"/>
+ </connections>
+ </menuItem>
+ <menuItem isSeparatorItem="YES" id="bNw-od-mp5"/>
+ <menuItem title="Check Spelling While Typing" id="rbD-Rh-wIN">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <connections>
+ <action selector="toggleContinuousSpellChecking:" target="-1" id="7w6-Qz-0kB"/>
+ </connections>
+ </menuItem>
+ <menuItem title="Check Grammar With Spelling" id="mK6-2p-4JG">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <connections>
+ <action selector="toggleGrammarChecking:" target="-1" id="muD-Qn-j4w"/>
+ </connections>
+ </menuItem>
+ <menuItem title="Correct Spelling Automatically" id="78Y-hA-62v">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <connections>
+ <action selector="toggleAutomaticSpellingCorrection:" target="-1" id="2lM-Qi-WAP"/>
+ </connections>
+ </menuItem>
+ </items>
+ </menu>
+ </menuItem>
+ <menuItem title="Substitutions" id="9ic-FL-obx">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <menu key="submenu" title="Substitutions" id="FeM-D8-WVr">
+ <items>
+ <menuItem title="Show Substitutions" id="z6F-FW-3nz">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <connections>
+ <action selector="orderFrontSubstitutionsPanel:" target="-1" id="oku-mr-iSq"/>
+ </connections>
+ </menuItem>
+ <menuItem isSeparatorItem="YES" id="gPx-C9-uUO"/>
+ <menuItem title="Smart Copy/Paste" id="9yt-4B-nSM">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <connections>
+ <action selector="toggleSmartInsertDelete:" target="-1" id="3IJ-Se-DZD"/>
+ </connections>
+ </menuItem>
+ <menuItem title="Smart Quotes" id="hQb-2v-fYv">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <connections>
+ <action selector="toggleAutomaticQuoteSubstitution:" target="-1" id="ptq-xd-QOA"/>
+ </connections>
+ </menuItem>
+ <menuItem title="Smart Dashes" id="rgM-f4-ycn">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <connections>
+ <action selector="toggleAutomaticDashSubstitution:" target="-1" id="oCt-pO-9gS"/>
+ </connections>
+ </menuItem>
+ <menuItem title="Smart Links" id="cwL-P1-jid">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <connections>
+ <action selector="toggleAutomaticLinkDetection:" target="-1" id="Gip-E3-Fov"/>
+ </connections>
+ </menuItem>
+ <menuItem title="Data Detectors" id="tRr-pd-1PS">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <connections>
+ <action selector="toggleAutomaticDataDetection:" target="-1" id="R1I-Nq-Kbl"/>
+ </connections>
+ </menuItem>
+ <menuItem title="Text Replacement" id="HFQ-gK-NFA">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <connections>
+ <action selector="toggleAutomaticTextReplacement:" target="-1" id="DvP-Fe-Py6"/>
+ </connections>
+ </menuItem>
+ </items>
+ </menu>
+ </menuItem>
+ <menuItem title="Transformations" id="2oI-Rn-ZJC">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <menu key="submenu" title="Transformations" id="c8a-y6-VQd">
+ <items>
+ <menuItem title="Make Upper Case" id="vmV-6d-7jI">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <connections>
+ <action selector="uppercaseWord:" target="-1" id="sPh-Tk-edu"/>
+ </connections>
+ </menuItem>
+ <menuItem title="Make Lower Case" id="d9M-CD-aMd">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <connections>
+ <action selector="lowercaseWord:" target="-1" id="iUZ-b5-hil"/>
+ </connections>
+ </menuItem>
+ <menuItem title="Capitalize" id="UEZ-Bs-lqG">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <connections>
+ <action selector="capitalizeWord:" target="-1" id="26H-TL-nsh"/>
+ </connections>
+ </menuItem>
+ </items>
+ </menu>
+ </menuItem>
+ <menuItem title="Speech" id="xrE-MZ-jX0">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <menu key="submenu" title="Speech" id="3rS-ZA-NoH">
+ <items>
+ <menuItem title="Start Speaking" id="Ynk-f8-cLZ">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <connections>
+ <action selector="startSpeaking:" target="-1" id="654-Ng-kyl"/>
+ </connections>
+ </menuItem>
+ <menuItem title="Stop Speaking" id="Oyz-dy-DGm">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <connections>
+ <action selector="stopSpeaking:" target="-1" id="dX8-6p-jy9"/>
+ </connections>
+ </menuItem>
+ </items>
+ </menu>
+ </menuItem>
+ </items>
+ </menu>
+ </menuItem>
+ <menuItem title="View" id="H8h-7b-M4v">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <menu key="submenu" title="View" id="HyV-fh-RgO">
+ <items>
+ <menuItem title="Enter Full Screen" keyEquivalent="f" id="4J7-dP-txa">
+ <modifierMask key="keyEquivalentModifierMask" control="YES" command="YES"/>
+ <connections>
+ <action selector="toggleFullScreen:" target="-1" id="dU3-MA-1Rq"/>
+ </connections>
+ </menuItem>
+ </items>
+ </menu>
+ </menuItem>
+ <menuItem title="Window" id="aUF-d1-5bR">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <menu key="submenu" title="Window" systemMenu="window" id="Td7-aD-5lo">
+ <items>
+ <menuItem title="Minimize" keyEquivalent="m" id="OY7-WF-poV">
+ <connections>
+ <action selector="performMiniaturize:" target="-1" id="VwT-WD-YPe"/>
+ </connections>
+ </menuItem>
+ <menuItem title="Zoom" id="R4o-n2-Eq4">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <connections>
+ <action selector="performZoom:" target="-1" id="DIl-cC-cCs"/>
+ </connections>
+ </menuItem>
+ <menuItem isSeparatorItem="YES" id="eu3-7i-yIM"/>
+ <menuItem title="Bring All to Front" id="LE2-aR-0XJ">
+ <modifierMask key="keyEquivalentModifierMask"/>
+ <connections>
+ <action selector="arrangeInFront:" target="-1" id="DRN-fu-gQh"/>
+ </connections>
+ </menuItem>
+ </items>
+ </menu>
+ </menuItem>
+ </items>
+ <point key="canvasLocation" x="142" y="-258"/>
+ </menu>
+ <window title="APP_NAME" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" releasedWhenClosed="NO" animationBehavior="default" id="QvC-M9-y7g" customClass="MainFlutterWindow" customModule="Runner" customModuleProvider="target">
+ <windowStyleMask key="styleMask" titled="YES" closable="YES" miniaturizable="YES" resizable="YES"/>
+ <rect key="contentRect" x="335" y="390" width="800" height="600"/>
+ <rect key="screenRect" x="0.0" y="0.0" width="2560" height="1577"/>
+ <view key="contentView" wantsLayer="YES" id="EiT-Mj-1SZ">
+ <rect key="frame" x="0.0" y="0.0" width="800" height="600"/>
+ <autoresizingMask key="autoresizingMask"/>
+ </view>
+ </window>
+ </objects>
+</document>
diff --git a/packages/audio_service/example/macos/Runner/Configs/AppInfo.xcconfig b/packages/audio_service/example/macos/Runner/Configs/AppInfo.xcconfig
new file mode 100644
index 00000000..ff690028
--- /dev/null
+++ b/packages/audio_service/example/macos/Runner/Configs/AppInfo.xcconfig
@@ -0,0 +1,14 @@
+// Application-level settings for the Runner target.
+//
+// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the
+// future. If not, the values below would default to using the project name when this becomes a
+// 'flutter create' template.
+
+// The application's name. By default this is also the title of the Flutter window.
+PRODUCT_NAME = example
+
+// The application's bundle identifier
+PRODUCT_BUNDLE_IDENTIFIER = com.ryanheise.example
+
+// The copyright displayed in application information
+PRODUCT_COPYRIGHT = Copyright © 2020 com.ryanheise. All rights reserved.
diff --git a/packages/audio_service/example/macos/Runner/Configs/Debug.xcconfig b/packages/audio_service/example/macos/Runner/Configs/Debug.xcconfig
new file mode 100644
index 00000000..36b0fd94
--- /dev/null
+++ b/packages/audio_service/example/macos/Runner/Configs/Debug.xcconfig
@@ -0,0 +1,2 @@
+#include "../../Flutter/Flutter-Debug.xcconfig"
+#include "Warnings.xcconfig"
diff --git a/packages/audio_service/example/macos/Runner/Configs/Release.xcconfig b/packages/audio_service/example/macos/Runner/Configs/Release.xcconfig
new file mode 100644
index 00000000..dff4f495
--- /dev/null
+++ b/packages/audio_service/example/macos/Runner/Configs/Release.xcconfig
@@ -0,0 +1,2 @@
+#include "../../Flutter/Flutter-Release.xcconfig"
+#include "Warnings.xcconfig"
diff --git a/packages/audio_service/example/macos/Runner/Configs/Warnings.xcconfig b/packages/audio_service/example/macos/Runner/Configs/Warnings.xcconfig
new file mode 100644
index 00000000..42bcbf47
--- /dev/null
+++ b/packages/audio_service/example/macos/Runner/Configs/Warnings.xcconfig
@@ -0,0 +1,13 @@
+WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings
+GCC_WARN_UNDECLARED_SELECTOR = YES
+CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES
+CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE
+CLANG_WARN__DUPLICATE_METHOD_MATCH = YES
+CLANG_WARN_PRAGMA_PACK = YES
+CLANG_WARN_STRICT_PROTOTYPES = YES
+CLANG_WARN_COMMA = YES
+GCC_WARN_STRICT_SELECTOR_MATCH = YES
+CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES
+CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES
+GCC_WARN_SHADOW = YES
+CLANG_WARN_UNREACHABLE_CODE = YES
diff --git a/packages/audio_service/example/macos/Runner/DebugProfile.entitlements b/packages/audio_service/example/macos/Runner/DebugProfile.entitlements
new file mode 100644
index 00000000..c946719a
--- /dev/null
+++ b/packages/audio_service/example/macos/Runner/DebugProfile.entitlements
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>com.apple.security.app-sandbox</key>
+ <true/>
+ <key>com.apple.security.cs.allow-jit</key>
+ <true/>
+ <key>com.apple.security.network.server</key>
+ <true/>
+ <key>com.apple.security.network.client</key>
+ <true/>
+</dict>
+</plist>
diff --git a/packages/audio_service/example/macos/Runner/Info.plist b/packages/audio_service/example/macos/Runner/Info.plist
new file mode 100644
index 00000000..4789daa6
--- /dev/null
+++ b/packages/audio_service/example/macos/Runner/Info.plist
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>$(DEVELOPMENT_LANGUAGE)</string>
+ <key>CFBundleExecutable</key>
+ <string>$(EXECUTABLE_NAME)</string>
+ <key>CFBundleIconFile</key>
+ <string></string>
+ <key>CFBundleIdentifier</key>
+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string>$(PRODUCT_NAME)</string>
+ <key>CFBundlePackageType</key>
+ <string>APPL</string>
+ <key>CFBundleShortVersionString</key>
+ <string>$(FLUTTER_BUILD_NAME)</string>
+ <key>CFBundleVersion</key>
+ <string>$(FLUTTER_BUILD_NUMBER)</string>
+ <key>LSMinimumSystemVersion</key>
+ <string>$(MACOSX_DEPLOYMENT_TARGET)</string>
+ <key>NSHumanReadableCopyright</key>
+ <string>$(PRODUCT_COPYRIGHT)</string>
+ <key>NSMainNibFile</key>
+ <string>MainMenu</string>
+ <key>NSPrincipalClass</key>
+ <string>NSApplication</string>
+</dict>
+</plist>
diff --git a/packages/audio_service/example/macos/Runner/MainFlutterWindow.swift b/packages/audio_service/example/macos/Runner/MainFlutterWindow.swift
new file mode 100644
index 00000000..2722837e
--- /dev/null
+++ b/packages/audio_service/example/macos/Runner/MainFlutterWindow.swift
@@ -0,0 +1,15 @@
+import Cocoa
+import FlutterMacOS
+
+class MainFlutterWindow: NSWindow {
+ override func awakeFromNib() {
+ let flutterViewController = FlutterViewController.init()
+ let windowFrame = self.frame
+ self.contentViewController = flutterViewController
+ self.setFrame(windowFrame, display: true)
+
+ RegisterGeneratedPlugins(registry: flutterViewController)
+
+ super.awakeFromNib()
+ }
+}
diff --git a/packages/audio_service/example/macos/Runner/Release.entitlements b/packages/audio_service/example/macos/Runner/Release.entitlements
new file mode 100644
index 00000000..48271acc
--- /dev/null
+++ b/packages/audio_service/example/macos/Runner/Release.entitlements
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>com.apple.security.app-sandbox</key>
+ <true/>
+ <key>com.apple.security.network.client</key>
+ <true/>
+</dict>
+</plist>
diff --git a/packages/audio_service/example/pubspec.yaml b/packages/audio_service/example/pubspec.yaml
new file mode 100644
index 00000000..b06fb77f
--- /dev/null
+++ b/packages/audio_service/example/pubspec.yaml
@@ -0,0 +1,32 @@
+name: audio_service_example
+description: Demonstrates how to use the audio_service plugin.
+publish_to: 'none'
+
+environment:
+ sdk: ">=3.3.0 <4.0.0"
+
+dependencies:
+ flutter:
+ sdk: flutter
+
+ path_provider: ^2.0.1
+ audio_session: ^0.1.25
+ just_audio: ^0.9.46
+ flutter_tts: ^3.8.3
+ device_info_plus: ^9.1.0
+ android_content_provider: ^0.4.1
+ permission_handler : ^11.0.1
+ rxdart: ^0.27.2
+ audio_service:
+ path: ../
+ audio_service_mpris: ^0.1.3
+ just_audio_mpv: ^0.1.7
+
+dev_dependencies:
+ flutter_test:
+ sdk: flutter
+ flutter_lints: ^3.0.1
+
+flutter:
+ # disable-swift-package-manager: true
+ uses-material-design: true
\ No newline at end of file
diff --git a/packages/audio_service/example/test/widget_test.dart b/packages/audio_service/example/test/widget_test.dart
new file mode 100644
index 00000000..cd0d69f2
--- /dev/null
+++ b/packages/audio_service/example/test/widget_test.dart
@@ -0,0 +1,25 @@
+// This is a basic Flutter widget test.
+// To perform an interaction with a widget in your test, use the WidgetTester utility that Flutter
+// provides. For example, you can send tap and scroll gestures. You can also use WidgetTester to
+// find child widgets in the widget tree, read text, and verify that the values of widget properties
+// are correct.
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+import 'package:audio_service_example/main.dart';
+
+void main() {
+ testWidgets('Verify Platform version', (WidgetTester tester) async {
+ // Build our app and trigger a frame.
+ await tester.pumpWidget(const MyApp());
+
+ // Verify that platform version is retrieved.
+ expect(
+ find.byWidgetPredicate(
+ (Widget widget) =>
+ widget is Text && widget.data!.startsWith('Running on:'),
+ ),
+ findsOneWidget);
+ });
+}
diff --git a/packages/audio_service/example/web/favicon.png b/packages/audio_service/example/web/favicon.png
new file mode 100644
index 00000000..8aaa46ac
Binary files /dev/null and b/packages/audio_service/example/web/favicon.png differ
diff --git a/packages/audio_service/example/web/icons/Icon-192.png b/packages/audio_service/example/web/icons/Icon-192.png
new file mode 100644
index 00000000..b749bfef
Binary files /dev/null and b/packages/audio_service/example/web/icons/Icon-192.png differ
diff --git a/packages/audio_service/example/web/icons/Icon-512.png b/packages/audio_service/example/web/icons/Icon-512.png
new file mode 100644
index 00000000..88cfd48d
Binary files /dev/null and b/packages/audio_service/example/web/icons/Icon-512.png differ
diff --git a/packages/audio_service/example/web/index.html b/packages/audio_service/example/web/index.html
new file mode 100644
index 00000000..012a92a2
--- /dev/null
+++ b/packages/audio_service/example/web/index.html
@@ -0,0 +1,25 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <base href="$FLUTTER_BASE_HREF">
+
+ <meta charset="UTF-8">
+ <meta content="IE=Edge" http-equiv="X-UA-Compatible">
+ <meta name="description" content="A new Flutter project.">
+
+ <!-- iOS meta tags & icons -->
+ <meta name="apple-mobile-web-app-capable" content="yes">
+ <meta name="apple-mobile-web-app-status-bar-style" content="black">
+ <meta name="apple-mobile-web-app-title" content="example">
+ <link rel="apple-touch-icon" href="icons/Icon-192.png">
+
+ <!-- Favicon -->
+ <link rel="icon" type="image/png" href="favicon.png"/>
+
+ <title>example</title>
+ <link rel="manifest" href="manifest.json">
+</head>
+<body>
+<script src="flutter_bootstrap.js" async></script>
+</body>
+</html>
diff --git a/packages/audio_service/example/web/manifest.json b/packages/audio_service/example/web/manifest.json
new file mode 100644
index 00000000..8c012917
--- /dev/null
+++ b/packages/audio_service/example/web/manifest.json
@@ -0,0 +1,23 @@
+{
+ "name": "example",
+ "short_name": "example",
+ "start_url": ".",
+ "display": "standalone",
+ "background_color": "#0175C2",
+ "theme_color": "#0175C2",
+ "description": "A new Flutter project.",
+ "orientation": "portrait-primary",
+ "prefer_related_applications": false,
+ "icons": [
+ {
+ "src": "icons/Icon-192.png",
+ "sizes": "192x192",
+ "type": "image/png"
+ },
+ {
+ "src": "icons/Icon-512.png",
+ "sizes": "512x512",
+ "type": "image/png"
+ }
+ ]
+}
diff --git a/packages/audio_service/lib/audio_service.dart b/packages/audio_service/lib/audio_service.dart
new file mode 100644
index 00000000..3104d7be
--- /dev/null
+++ b/packages/audio_service/lib/audio_service.dart
@@ -0,0 +1,4060 @@
+// ignore_for_file: close_sinks
+
+import 'dart:async';
+import 'dart:isolate';
+import 'dart:ui';
+
+import 'package:audio_service_platform_interface/audio_service_platform_interface.dart';
+import 'package:audio_session/audio_session.dart';
+import 'package:clock/clock.dart';
+import 'package:flutter/foundation.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_cache_manager/flutter_cache_manager.dart';
+import 'package:rxdart/rxdart.dart';
+
+AudioServicePlatform _platform = AudioServicePlatform.instance;
+
+/// The buttons on a headset.
+enum MediaButton {
+ /// The "media" button on Android, or the play/pause button on iOS.
+ media,
+
+ /// The "skip to next" button.
+ next,
+
+ /// The "skip to previous" button.
+ previous,
+}
+
+/// The actions associated with playing audio.
+enum MediaAction {
+ /// Stop playing audio.
+ stop,
+
+ /// Pause audio.
+ pause,
+
+ /// Play or resume audio.
+ play,
+
+ /// Rewind.
+ rewind,
+
+ /// Skip to the previous media item.
+ skipToPrevious,
+
+ /// Skip to the next media item.
+ skipToNext,
+
+ /// Fast forward.
+ fastForward,
+
+ /// Set a rating for the current media item.
+ setRating,
+
+ /// Seek within the current media item.
+ seek,
+
+ /// Toggle between playing and paused.
+ playPause,
+
+ /// Play a given media item by ID.
+ playFromMediaId,
+
+ /// Play media from a search.
+ playFromSearch,
+
+ /// Skip to a queue item.
+ skipToQueueItem,
+
+ /// Play media from a URI.
+ playFromUri,
+
+ /// Prepare media for playback.
+ prepare,
+
+ /// Prepare media for playback by ID.
+ prepareFromMediaId,
+
+ /// Prepare media for playback from a search.
+ prepareFromSearch,
+
+ /// Prepare media for playback from a URI.
+ prepareFromUri,
+
+ /// Set the repeat mode.
+ setRepeatMode,
+
+ /// Was depreceated in Android.
+ // ignore: unused_field
+ _setShuffleModeEnabled,
+
+ /// Set captioning enabled.
+ setCaptioningEnabled,
+
+ /// Set the shuffle mode.
+ setShuffleMode,
+
+ /// Seek backwards continuously.
+ seekBackward,
+
+ /// Seek forwards continuously.
+ seekForward,
+
+ /// Set speed.
+ setSpeed,
+
+ /// Custom MediaAction.
+ custom,
+}
+
+/// The states of audio processing.
+enum AudioProcessingState {
+ /// There hasn't been any resource loaded yet.
+ idle,
+
+ /// Resource is being loaded.
+ loading,
+
+ /// Resource is being buffered.
+ buffering,
+
+ /// Resource is buffered enough and available for playback.
+ ready,
+
+ /// The end of resource was reached.
+ completed,
+
+ /// There was an error loading resource.
+ ///
+ /// [PlaybackState.errorCode] and [PlaybackState.errorMessage] will be not null
+ /// in this state.
+ error,
+}
+
+/// The playback state which includes a [playing] boolean state, a processing
+/// state such as [AudioProcessingState.buffering], the playback position and
+/// the currently enabled actions to be shown in the Android notification or the
+/// iOS control center.
+class PlaybackState {
+ /// The audio processing state e.g. [AudioProcessingState.buffering].
+ final AudioProcessingState processingState;
+
+ /// Whether audio is either playing, or will play as soon as [processingState]
+ /// is [AudioProcessingState.ready]. A true value should be broadcast whenever
+ /// it would be appropriate for UIs to display a pause or stop button.
+ ///
+ /// Since [playing] and [processingState] can vary independently, it is
+ /// possible distinguish a particular audio processing state while audio is
+ /// playing vs paused. For example, when buffering occurs during a seek, the
+ /// [processingState] can be [AudioProcessingState.buffering], but alongside
+ /// that [playing] can be true to indicate that the seek was performed while
+ /// playing, or false to indicate that the seek was performed while paused.
+ final bool playing;
+
+ /// The list of currently enabled controls which should be shown in the media
+ /// notification. Each control represents a clickable button with a
+ /// [MediaAction] that must be one of:
+ ///
+ /// * [MediaAction.stop]
+ /// * [MediaAction.pause]
+ /// * [MediaAction.play]
+ /// * [MediaAction.rewind]
+ /// * [MediaAction.skipToPrevious]
+ /// * [MediaAction.skipToNext]
+ /// * [MediaAction.fastForward]
+ /// * [MediaAction.playPause]
+ final List<MediaControl> controls;
+
+ /// Up to 3 indices of the [controls] that should appear in Android's compact
+ /// media notification view. When the notification is expanded, all [controls]
+ /// will be shown.
+ final List<int>? androidCompactActionIndices;
+
+ /// The set of system actions currently enabled. This is for specifying any
+ /// other [MediaAction]s that are not supported by [controls], because they do
+ /// not represent clickable buttons. For example:
+ ///
+ /// * [MediaAction.seek] (enable a seek bar)
+ /// * [MediaAction.seekForward] (enable press-and-hold fast-forward control)
+ /// * [MediaAction.seekBackward] (enable press-and-hold rewind control)
+ ///
+ /// Note that specifying [MediaAction.seek] in [systemActions] will enable a
+ /// seek bar in both the Android notification and the iOS control center, but
+ /// on Android, it will show only if the media item's duration has been set.
+ /// [MediaAction.seekForward] and [MediaAction.seekBackward] have a special
+ /// behaviour on iOS in which if you have already enabled the
+ /// [MediaAction.skipToNext] and [MediaAction.skipToPrevious] buttons, these
+ /// additional actions will allow the user to press and hold the buttons to
+ /// activate the continuous seeking behaviour.
+ ///
+ /// When enabling the seek bar, also note that some Android devices will not
+ /// render the seek bar correctly unless your [AudioServiceConfig.androidNotificationIcon]
+ /// is a monochrome white icon on a transparent background, and your
+ /// [AudioServiceConfig.notificationColor] is a non-transparent color.
+ final Set<MediaAction> systemActions;
+
+ /// The playback position at [updateTime].
+ ///
+ /// For efficiency, the [updatePosition] should NOT be updated continuously in
+ /// real time. Instead, it should be updated only when the normal continuity
+ /// of time is disrupted, such as during a seek, buffering and seeking. When
+ /// broadcasting such a position change, the [updateTime] specifies the time
+ /// of that change, allowing clients to project the realtime value of the
+ /// position as `position + (DateTime.now() - updateTime)`. As a convenience,
+ /// this calculation is provided by the [position] getter.
+ final Duration updatePosition;
+
+ /// The buffered position.
+ final Duration bufferedPosition;
+
+ /// The current playback speed where 1.0 means normal speed.
+ final double speed;
+
+ /// The time at which the playback position was last updated.
+ final DateTime updateTime;
+
+ /// The error code when [processingState] is [AudioProcessingState.error].
+ final int? errorCode;
+
+ /// The error message when [processingState] is [AudioProcessingState.error].
+ final String? errorMessage;
+
+ /// The current repeat mode.
+ final AudioServiceRepeatMode repeatMode;
+
+ /// The current shuffle mode.
+ final AudioServiceShuffleMode shuffleMode;
+
+ /// Whether captioning is enabled.
+ final bool captioningEnabled;
+
+ /// The index of the current item in the queue, if any.
+ final int? queueIndex;
+
+ /// Creates a [PlaybackState] with given field values, and with [updateTime]
+ /// defaulting to [DateTime.now].
+ PlaybackState({
+ this.processingState = AudioProcessingState.idle,
+ this.playing = false,
+ this.controls = const [],
+ this.androidCompactActionIndices,
+ this.systemActions = const {},
+ this.updatePosition = Duration.zero,
+ this.bufferedPosition = Duration.zero,
+ this.speed = 1.0,
+ DateTime? updateTime,
+ this.errorCode,
+ this.errorMessage,
+ this.repeatMode = AudioServiceRepeatMode.none,
+ this.shuffleMode = AudioServiceShuffleMode.none,
+ this.captioningEnabled = false,
+ this.queueIndex,
+ }) : assert(androidCompactActionIndices == null ||
+ androidCompactActionIndices.length <= 3),
+ updateTime = updateTime ?? clock.now();
+
+ /// Creates a copy of this state with given fields replaced by new values,
+ /// with [updateTime] set to [DateTime.now], and unless otherwise replaced,
+ /// with [updatePosition] set to [position].
+ ///
+ /// The [errorCode] and [errorMessage] will be set to null unless [processingState] is
+ /// [AudioProcessingState.error].
+ PlaybackStateCopyWith get copyWith => _PlaybackStateCopyWith(this);
+
+ /// The current playback position.
+ Duration get position {
+ if (playing && processingState == AudioProcessingState.ready) {
+ return Duration(
+ milliseconds: (updatePosition.inMilliseconds +
+ speed *
+ (clock.now().millisecondsSinceEpoch -
+ updateTime.millisecondsSinceEpoch))
+ .toInt(),
+ );
+ } else {
+ return updatePosition;
+ }
+ }
+
+ PlaybackStateMessage _toMessage() => PlaybackStateMessage(
+ processingState:
+ AudioProcessingStateMessage.values[processingState.index],
+ playing: playing,
+ controls: controls.map((control) => control._toMessage()).toList(),
+ androidCompactActionIndices: androidCompactActionIndices,
+ systemActions: systemActions
+ .map((action) => MediaActionMessage.values[action.index])
+ .toSet(),
+ updatePosition: updatePosition,
+ bufferedPosition: bufferedPosition,
+ speed: speed,
+ updateTime: updateTime,
+ errorCode: errorCode,
+ errorMessage: errorMessage,
+ repeatMode: AudioServiceRepeatModeMessage.values[repeatMode.index],
+ shuffleMode: AudioServiceShuffleModeMessage.values[shuffleMode.index],
+ captioningEnabled: captioningEnabled,
+ queueIndex: queueIndex,
+ );
+
+ @override
+ String toString() => '${_toMessage().toMap()}';
+
+ @override
+ int get hashCode => Object.hash(
+ processingState,
+ playing,
+ Object.hashAll(controls),
+ androidCompactActionIndices != null
+ ? Object.hashAll(androidCompactActionIndices!)
+ : 0,
+ Object.hashAll(systemActions),
+ updatePosition,
+ bufferedPosition,
+ speed,
+ updateTime,
+ errorCode,
+ errorMessage,
+ repeatMode,
+ shuffleMode,
+ captioningEnabled,
+ queueIndex,
+ );
+
+ @override
+ bool operator ==(Object other) =>
+ identical(other, this) ||
+ other.runtimeType == runtimeType &&
+ other is PlaybackState &&
+ processingState == other.processingState &&
+ playing == other.playing &&
+ listEquals(controls, other.controls) &&
+ listEquals(
+ androidCompactActionIndices, other.androidCompactActionIndices) &&
+ setEquals(systemActions, other.systemActions) &&
+ updatePosition == other.updatePosition &&
+ bufferedPosition == other.bufferedPosition &&
+ speed == other.speed &&
+ updateTime == other.updateTime &&
+ errorCode == other.errorCode &&
+ errorMessage == other.errorMessage &&
+ repeatMode == other.repeatMode &&
+ shuffleMode == other.shuffleMode &&
+ captioningEnabled == other.captioningEnabled &&
+ queueIndex == other.queueIndex;
+}
+
+/// The `copyWith` function type for [PlaybackState].
+abstract class PlaybackStateCopyWith {
+ /// Calls this function.
+ PlaybackState call({
+ AudioProcessingState processingState,
+ bool playing,
+ List<MediaControl> controls,
+ List<int>? androidCompactActionIndices,
+ Set<MediaAction> systemActions,
+ Duration updatePosition,
+ Duration bufferedPosition,
+ double speed,
+ int? errorCode,
+ String? errorMessage,
+ AudioServiceRepeatMode repeatMode,
+ AudioServiceShuffleMode shuffleMode,
+ bool captioningEnabled,
+ int? queueIndex,
+ });
+}
+
+/// The implementation of [PlaybackState]'s `copyWith` function allowing
+/// parameters to be explicitly set to null.
+class _PlaybackStateCopyWith extends PlaybackStateCopyWith {
+ static const _fakeNull = Object();
+
+ /// The [PlaybackState] object this function applies to.
+ final PlaybackState value;
+
+ _PlaybackStateCopyWith(this.value);
+
+ @override
+ PlaybackState call({
+ Object? processingState = _fakeNull,
+ Object? playing = _fakeNull,
+ Object? controls = _fakeNull,
+ Object? androidCompactActionIndices = _fakeNull,
+ Object? systemActions = _fakeNull,
+ Object? updatePosition = _fakeNull,
+ Object? bufferedPosition = _fakeNull,
+ Object? speed = _fakeNull,
+ Object? errorCode = _fakeNull,
+ Object? errorMessage = _fakeNull,
+ Object? repeatMode = _fakeNull,
+ Object? shuffleMode = _fakeNull,
+ Object? captioningEnabled = _fakeNull,
+ Object? queueIndex = _fakeNull,
+ }) =>
+ PlaybackState(
+ processingState: processingState == _fakeNull
+ ? value.processingState
+ : processingState as AudioProcessingState,
+ playing: playing == _fakeNull ? value.playing : playing as bool,
+ controls: controls == _fakeNull
+ ? value.controls
+ : controls as List<MediaControl>,
+ androidCompactActionIndices: androidCompactActionIndices == _fakeNull
+ ? value.androidCompactActionIndices
+ : androidCompactActionIndices as List<int>?,
+ systemActions: systemActions == _fakeNull
+ ? value.systemActions
+ : systemActions as Set<MediaAction>,
+ updatePosition: updatePosition == _fakeNull
+ ? value.updatePosition
+ : updatePosition as Duration,
+ bufferedPosition: bufferedPosition == _fakeNull
+ ? value.bufferedPosition
+ : bufferedPosition as Duration,
+ speed: speed == _fakeNull ? value.speed : speed as double,
+ errorCode: errorCode == _fakeNull ? value.errorCode : errorCode as int?,
+ errorMessage: errorMessage == _fakeNull
+ ? value.errorMessage
+ : errorMessage as String?,
+ repeatMode: repeatMode == _fakeNull
+ ? value.repeatMode
+ : repeatMode as AudioServiceRepeatMode,
+ shuffleMode: shuffleMode == _fakeNull
+ ? value.shuffleMode
+ : shuffleMode as AudioServiceShuffleMode,
+ captioningEnabled: captioningEnabled == _fakeNull
+ ? value.captioningEnabled
+ : captioningEnabled as bool,
+ queueIndex:
+ queueIndex == _fakeNull ? value.queueIndex : queueIndex as int?,
+ );
+}
+
+/// The style of a [Rating].
+enum RatingStyle {
+ /// Indicates a rating style is not supported.
+ ///
+ /// A [Rating] will never have this type, but can be used by other classes
+ /// to indicate they do not support [Rating].
+ none,
+
+ /// A rating style with a single degree of rating, "heart" vs "no heart".
+ ///
+ /// Can be used to indicate the content referred to is a favorite (or not).
+ heart,
+
+ /// A rating style for "thumb up" vs "thumb down".
+ thumbUpDown,
+
+ /// A rating style with 0 to 3 stars.
+ range3stars,
+
+ /// A rating style with 0 to 4 stars.
+ range4stars,
+
+ /// A rating style with 0 to 5 stars.
+ range5stars,
+
+ /// A rating style expressed as a percentage.
+ percentage,
+}
+
+/// A rating to attach to a MediaItem.
+class Rating {
+ final RatingStyle _type;
+ final Object? _value;
+
+ const Rating._(this._type, this._value);
+
+ /// Creates a new heart rating.
+ const Rating.newHeartRating(bool hasHeart)
+ : this._(RatingStyle.heart, hasHeart);
+
+ /// Creates a new percentage rating.
+ const Rating.newPercentageRating(double percent)
+ : assert(
+ percent >= 0 && percent <= 100,
+ 'Percentage must be in range from 0 to 100',
+ ),
+ _type = RatingStyle.percentage,
+ _value = percent;
+
+ /// Creates a new star rating.
+ Rating.newStarRating(RatingStyle style, int rating)
+ : assert(
+ style == RatingStyle.range3stars ||
+ style == RatingStyle.range4stars ||
+ style == RatingStyle.range5stars,
+ 'Invalid rating style',
+ ),
+ assert(rating >= 0 && rating <= style.index),
+ _type = style,
+ _value = rating;
+
+ /// Creates a new thumb rating.
+ const Rating.newThumbRating(bool isThumbsUp)
+ : this._(RatingStyle.thumbUpDown, isThumbsUp);
+
+ /// Creates a new unrated rating.
+ const Rating.newUnratedRating(RatingStyle ratingStyle)
+ : this._(ratingStyle, null);
+
+ /// Return the rating style.
+ RatingStyle getRatingStyle() => _type;
+
+ /// Returns a percentage rating value greater or equal to `0.0`, or a
+ /// negative value if the rating style is not percentage-based, or
+ /// if it is unrated.
+ double getPercentRating() {
+ if (_type != RatingStyle.percentage) return -1;
+ final localValue = _value as double?;
+ if (localValue == null || localValue < 0 || localValue > 100) return -1;
+ return localValue;
+ }
+
+ /// Returns a rating value greater or equal to `0.0`, or a negative
+ /// value if the rating style is not star-based, or if it is
+ /// unrated.
+ int getStarRating() {
+ if (_type != RatingStyle.range3stars &&
+ _type != RatingStyle.range4stars &&
+ _type != RatingStyle.range5stars) {
+ return -1;
+ }
+ return _value as int? ?? -1;
+ }
+
+ /// Returns true if the rating is "heart selected" or false if the
+ /// rating is "heart unselected", if the rating style is not [RatingStyle.heart]
+ /// or if it is unrated.
+ bool hasHeart() {
+ if (_type != RatingStyle.heart) return false;
+ return _value as bool? ?? false;
+ }
+
+ /// Returns true if the rating is "thumb up" or false if the rating
+ /// is "thumb down", if the rating style is not [RatingStyle.thumbUpDown] or if
+ /// it is unrated.
+ bool isThumbUp() {
+ if (_type != RatingStyle.thumbUpDown) return false;
+ return _value as bool? ?? false;
+ }
+
+ /// Return whether there is a rating value available.
+ bool isRated() => _value != null;
+
+ RatingMessage _toMessage() => RatingMessage(
+ type: RatingStyleMessage.values[_type.index],
+ value: _value,
+ );
+
+ @override
+ String toString() => '${_toMessage().toMap()}';
+
+ @override
+ int get hashCode => Object.hash(_value, _type);
+
+ @override
+ bool operator ==(Object other) =>
+ other.runtimeType == runtimeType &&
+ other is Rating &&
+ _type == other._type &&
+ _value == other._value;
+}
+
+/// Metadata of an audio item that can be played, or a folder containing
+/// audio items.
+class MediaItem {
+ /// A unique id.
+ final String id;
+
+ /// The title of this media item.
+ final String title;
+
+ /// The album this media item belongs to.
+ final String? album;
+
+ /// The artist of this media item.
+ final String? artist;
+
+ /// The genre of this media item.
+ final String? genre;
+
+ /// The duration of this media item.
+ final Duration? duration;
+
+ /// The artwork URI for this media item.
+ ///
+ /// Supported types of URIs are:
+ ///
+ /// * File - file://
+ /// * Network - http:// https:// etc.
+ /// * Android content URIs - content://
+ ///
+ /// ## Speeding up Android content URI loading
+ ///
+ /// For Android content:// URIs, the plugin by default uses
+ /// `ContentResolver.openFileDescriptor`, which takes the direct URI of an
+ /// image.
+ ///
+ /// On Android API >= 29 there is `ContentResolver.loadThumbnail` function
+ /// which takes a URI of some content (for example, a song from `MediaStore`),
+ /// and returns a thumbnail for it.
+ ///
+ /// It is noticeably faster to use this function. You can enable this by
+ /// putting a `loadThumbnailUri` key into the [extras]. If `loadThumbnail` is
+ /// not available, it will just fallback to using `openFileDescriptor`.
+ final Uri? artUri;
+
+ /// The HTTP headers to use when sending an HTTP request for [artUri].
+ final Map<String, String>? artHeaders;
+
+ /// Whether this is playable (i.e. not a folder).
+ final bool? playable;
+
+ /// Override the default title for display purposes.
+ final String? displayTitle;
+
+ /// Override the default subtitle for display purposes.
+ final String? displaySubtitle;
+
+ /// Override the default description for display purposes.
+ final String? displayDescription;
+
+ /// The rating of the media item.
+ final Rating? rating;
+
+ /// Whether this is a live stream.
+ final bool? isLive;
+
+ /// A map of additional metadata for the media item.
+ ///
+ /// The values must be of type `int`, `String`, `bool` or `double`.
+ final Map<String, dynamic>? extras;
+
+ /// Creates a [MediaItem].
+ ///
+ /// The [id] must be unique for each instance.
+ const MediaItem({
+ required this.id,
+ required this.title,
+ this.album,
+ this.artist,
+ this.genre,
+ this.duration,
+ this.artUri,
+ this.artHeaders,
+ this.playable = true,
+ this.displayTitle,
+ this.displaySubtitle,
+ this.displayDescription,
+ this.rating,
+ this.isLive,
+ this.extras,
+ });
+
+ /// Creates a copy of this [MediaItem] with with the given fields replaced by
+ /// new values.
+ MediaItemCopyWith get copyWith => _MediaItemCopyWith(this);
+
+ @override
+ int get hashCode => id.hashCode;
+
+ @override
+ bool operator ==(Object other) =>
+ other.runtimeType == runtimeType && other is MediaItem && other.id == id;
+
+ MediaItemMessage _toMessage() => MediaItemMessage(
+ id: id,
+ album: album,
+ title: title,
+ artist: artist,
+ genre: genre,
+ duration: duration,
+ artUri: artUri,
+ playable: playable,
+ displayTitle: displayTitle,
+ displaySubtitle: displaySubtitle,
+ displayDescription: displayDescription,
+ rating: rating?._toMessage(),
+ isLive: isLive,
+ extras: extras,
+ );
+
+ @override
+ String toString() => '${_toMessage().toMap()}';
+}
+
+/// The `copyWith` function type for [MediaItem].
+abstract class MediaItemCopyWith {
+ /// Calls this function.
+ MediaItem call({
+ String id,
+ String title,
+ String? album,
+ String? artist,
+ String? genre,
+ Duration? duration,
+ Uri? artUri,
+ bool? playable,
+ String? displayTitle,
+ String? displaySubtitle,
+ String? displayDescription,
+ Rating? rating,
+ bool? isLive,
+ Map<String, dynamic>? extras,
+ });
+}
+
+/// The implementation of [MediaItem]'s `copyWith` function allowing
+/// parameters to be explicitly set to null.
+class _MediaItemCopyWith extends MediaItemCopyWith {
+ static const _fakeNull = Object();
+
+ /// The [MediaItem] object this function applies to.
+ final MediaItem value;
+
+ _MediaItemCopyWith(this.value);
+
+ @override
+ MediaItem call({
+ Object? id = _fakeNull,
+ Object? title = _fakeNull,
+ Object? album = _fakeNull,
+ Object? artist = _fakeNull,
+ Object? genre = _fakeNull,
+ Object? duration = _fakeNull,
+ Object? artUri = _fakeNull,
+ Object? playable = _fakeNull,
+ Object? displayTitle = _fakeNull,
+ Object? displaySubtitle = _fakeNull,
+ Object? displayDescription = _fakeNull,
+ Object? rating = _fakeNull,
+ Object? isLive = _fakeNull,
+ Object? extras = _fakeNull,
+ }) =>
+ MediaItem(
+ id: id == _fakeNull ? value.id : id as String,
+ title: title == _fakeNull ? value.title : title as String,
+ album: album == _fakeNull ? value.album : album as String?,
+ artist: artist == _fakeNull ? value.artist : artist as String?,
+ genre: genre == _fakeNull ? value.genre : genre as String?,
+ duration:
+ duration == _fakeNull ? value.duration : duration as Duration?,
+ artUri: artUri == _fakeNull ? value.artUri : artUri as Uri?,
+ playable: playable == _fakeNull ? value.playable : playable as bool?,
+ displayTitle: displayTitle == _fakeNull
+ ? value.displayTitle
+ : displayTitle as String?,
+ displaySubtitle: displaySubtitle == _fakeNull
+ ? value.displaySubtitle
+ : displaySubtitle as String?,
+ displayDescription: displayDescription == _fakeNull
+ ? value.displayDescription
+ : displayDescription as String?,
+ rating: rating == _fakeNull ? value.rating : rating as Rating?,
+ isLive: isLive == _fakeNull ? value.isLive : isLive as bool?,
+ extras: extras == _fakeNull
+ ? value.extras
+ : extras as Map<String, dynamic>?,
+ );
+}
+
+/// Custom action information used to define an action name and optional extras
+/// that are sent to [AudioHandler.customAction] when the associated media control is used.
+class CustomMediaAction {
+ /// Custom action name
+ final String name;
+
+ /// A map of additional data for the custom action.
+ ///
+ /// The values must be integers or strings.
+ final Map<String, dynamic>? extras;
+
+ /// Creates a [CustomMediaAction].
+ const CustomMediaAction({required this.name, this.extras});
+
+ /// Convert to a Map.
+ Map<String, dynamic> toMap() => <String, dynamic>{
+ 'name': name,
+ 'extras': extras,
+ };
+
+ CustomMediaActionMessage _toMessage() => CustomMediaActionMessage(
+ name: name,
+ extras: extras,
+ );
+
+ @override
+ int get hashCode => Object.hash(name, extras);
+
+ @override
+ bool operator ==(Object other) =>
+ other.runtimeType == runtimeType &&
+ other is CustomMediaAction &&
+ name == other.name &&
+ mapEquals<String, dynamic>(extras, other.extras);
+}
+
+/// A button to appear in the Android notification, lock screen, Android smart
+/// watch, or Android Auto device. The set of buttons you would like to display
+/// at any given moment should be streamed via [AudioHandler.playbackState].
+///
+/// Each [MediaControl] button controls a specified [MediaAction]. Only the
+/// following actions can be represented as buttons:
+///
+/// * [MediaAction.stop]
+/// * [MediaAction.pause]
+/// * [MediaAction.play]
+/// * [MediaAction.rewind]
+/// * [MediaAction.skipToPrevious]
+/// * [MediaAction.skipToNext]
+/// * [MediaAction.fastForward]
+/// * [MediaAction.playPause]
+///
+/// Predefined controls with default Android icons and labels are defined as
+/// static fields of this class. If you wish to define your own custom Android
+/// controls with your own icon resources, you will need to place the Android
+/// resources in `android/app/src/main/res`. Here, you will find a subdirectory
+/// for each different resolution:
+///
+/// ```
+/// drawable-hdpi
+/// drawable-mdpi
+/// drawable-xhdpi
+/// drawable-xxhdpi
+/// drawable-xxxhdpi
+/// ```
+///
+/// You can use [Android Asset
+/// Studio](https://romannurik.github.io/AndroidAssetStudio/) to generate these
+/// different subdirectories for any standard material design icon.
+class MediaControl {
+ /// A default control for [MediaAction.stop].
+ static const stop = MediaControl(
+ androidIcon: 'drawable/audio_service_stop',
+ label: 'Stop',
+ action: MediaAction.stop,
+ );
+
+ /// A default control for [MediaAction.pause].
+ static const pause = MediaControl(
+ androidIcon: 'drawable/audio_service_pause',
+ label: 'Pause',
+ action: MediaAction.pause,
+ );
+
+ /// A default control for [MediaAction.play].
+ static const play = MediaControl(
+ androidIcon: 'drawable/audio_service_play_arrow',
+ label: 'Play',
+ action: MediaAction.play,
+ );
+
+ /// A default control for [MediaAction.rewind].
+ static const rewind = MediaControl(
+ androidIcon: 'drawable/audio_service_fast_rewind',
+ label: 'Rewind',
+ action: MediaAction.rewind,
+ );
+
+ /// A default control for [MediaAction.skipToNext].
+ static const skipToNext = MediaControl(
+ androidIcon: 'drawable/audio_service_skip_next',
+ label: 'Next',
+ action: MediaAction.skipToNext,
+ );
+
+ /// A default control for [MediaAction.skipToPrevious].
+ static const skipToPrevious = MediaControl(
+ androidIcon: 'drawable/audio_service_skip_previous',
+ label: 'Previous',
+ action: MediaAction.skipToPrevious,
+ );
+
+ /// A default control for [MediaAction.fastForward].
+ static const fastForward = MediaControl(
+ androidIcon: 'drawable/audio_service_fast_forward',
+ label: 'Fast Forward',
+ action: MediaAction.fastForward,
+ );
+
+ /// A reference to an Android icon resource for the control (e.g.
+ /// `"drawable/ic_action_pause"`)
+ final String androidIcon;
+
+ /// A label for the control
+ final String label;
+
+ /// The action to be executed by this control
+ final MediaAction action;
+
+ /// The custom action name and optional extras to receive in
+ /// [AudioHandler.customAction]
+ final CustomMediaAction? customAction;
+
+ /// Creates a custom [MediaControl].
+ MediaControl.custom({
+ required this.androidIcon,
+ required this.label,
+ required String name,
+ Map<String, dynamic>? extras,
+ }) : action = MediaAction.custom,
+ customAction = CustomMediaAction(name: name, extras: extras) {
+ assert(action != MediaAction.custom || customAction != null);
+ }
+
+ /// Creates a custom [MediaControl].
+ const MediaControl({
+ required this.androidIcon,
+ required this.label,
+ required this.action,
+ this.customAction,
+ });
+
+ /// Creates a copy of this control with given fields replaced by new values.
+ MediaControl copyWith({
+ String? androidIcon,
+ String? label,
+ MediaAction? action,
+ CustomMediaAction? customAction,
+ }) =>
+ MediaControl(
+ androidIcon: androidIcon ?? this.androidIcon,
+ label: label ?? this.label,
+ action: action ?? this.action,
+ customAction: customAction ?? this.customAction,
+ );
+
+ MediaControlMessage _toMessage() => MediaControlMessage(
+ androidIcon: androidIcon,
+ label: label,
+ action: MediaActionMessage.values[action.index],
+ customAction: customAction?._toMessage(),
+ );
+
+ @override
+ String toString() => '${_toMessage().toMap()}';
+
+ @override
+ int get hashCode => Object.hash(androidIcon, label, action);
+
+ @override
+ bool operator ==(Object other) =>
+ other.runtimeType == runtimeType &&
+ other is MediaControl &&
+ androidIcon == other.androidIcon &&
+ label == other.label &&
+ action == other.action;
+}
+
+/// Provides an API to manage the app's [AudioHandler]. An app must call [init]
+/// during initialisation to register the [AudioHandler] that will service all
+/// requests to play audio.
+class AudioService {
+ /// The cache to use when loading artwork.
+ /// Defaults to [DefaultCacheManager].
+ static BaseCacheManager get cacheManager => _cacheManager!;
+ static BaseCacheManager? _cacheManager;
+
+ static late AudioServiceConfig _config;
+ static late AudioHandler _handler;
+
+ /// The current configuration.
+ static AudioServiceConfig get config => _config;
+
+ /// The root media ID for browsing media provided by the background
+ /// task.
+ static const String browsableRootId = 'root';
+
+ /// The root media ID for browsing the most recently played item(s).
+ static const String recentRootId = 'recent';
+
+ static final BehaviorSubject<bool> _notificationClicked =
+ BehaviorSubject.seeded(false);
+
+ /// A stream that broadcasts the status of the notificationClick event.
+ static ValueStream<bool> get notificationClicked => _notificationClicked;
+
+ static final _asyncError = PublishSubject<Object>();
+
+ /// A stream that broadcasts any exceptions that occur asynchronously.
+ static Stream<Object> get asyncError => _asyncError;
+
+ static final _compatibilitySwitcher = SwitchAudioHandler();
+
+ /// Register the app's [AudioHandler] with configuration options. This must be
+ /// called once during the app's initialisation so that it is prepared to
+ /// handle audio requests immediately after a cold restart (e.g. if the user
+ /// clicks on the play button in the media notification while your app is not
+ /// running and your app needs to be woken up).
+ ///
+ /// You may optionally specify a [cacheManager] to use when loading artwork to
+ /// display in the media notification and lock screen. This defaults to
+ /// [DefaultCacheManager].
+ ///
+ /// This may throw a [PlatformException] on Android if you have not set the
+ /// correct Service or Activity in your `AndroidManifest.xml` file or if your
+ /// Activity does not provide the correct `FlutterEngine`.
+ static Future<T> init<T extends AudioHandler>({
+ required T Function() builder,
+ AudioServiceConfig? config,
+ BaseCacheManager? cacheManager,
+ }) async {
+ assert(_cacheManager == null);
+ config ??= const AudioServiceConfig();
+ assert(config.fastForwardInterval > Duration.zero);
+ assert(config.rewindInterval > Duration.zero);
+ WidgetsFlutterBinding.ensureInitialized();
+ _cacheManager = (cacheManager ??= DefaultCacheManager());
+ final callbacks = _HandlerCallbacks();
+ _platform.setHandlerCallbacks(callbacks);
+ await _platform.configure(ConfigureRequest(config: config._toMessage()));
+ _config = config;
+ final handler = builder();
+ _handler = handler;
+ callbacks.setHandler(handler);
+
+ _observeMediaItem();
+ _observeAndroidPlaybackInfo();
+ _observeQueue();
+ _observePlaybackState();
+
+ return handler;
+ }
+
+ static Future<void> _observeMediaItem() async {
+ Object? artFetchOperationId;
+ _handler.mediaItem.listen((mediaItem) async {
+ if (mediaItem == null) {
+ return;
+ }
+ final operationId = Object();
+ artFetchOperationId = operationId;
+ final artUri = mediaItem.artUri;
+ if (artUri == null || artUri.scheme == 'content') {
+ _platform
+ .setMediaItem(
+ SetMediaItemRequest(mediaItem: mediaItem._toMessage()))
+ .catchError(_asyncError.add);
+ } else {
+ /// Sends media item to the platform.
+ /// We potentially need to fetch the art before that.
+ Future<void> sendToPlatform(String? filePath) async {
+ final extras = mediaItem.extras;
+ final platformMediaItem = mediaItem.copyWith(
+ extras: <String, dynamic>{
+ if (extras != null) ...extras,
+ 'artCacheFile': filePath,
+ },
+ );
+ await _platform.setMediaItem(
+ SetMediaItemRequest(mediaItem: platformMediaItem._toMessage()));
+ }
+
+ if (artUri.scheme == 'file') {
+ sendToPlatform(artUri.toFilePath()).catchError(_asyncError.add);
+ } else {
+ // Try to load a cached file from memory.
+ final fileInfo =
+ await cacheManager.getFileFromMemory(artUri.toString());
+ final filePath = fileInfo?.file.path;
+ if (operationId != artFetchOperationId) {
+ return;
+ }
+
+ if (filePath != null) {
+ // If we successfully downloaded the art call to platform.
+ sendToPlatform(filePath).catchError(_asyncError.add);
+ } else {
+ // We haven't fetched the art yet, so show the metadata now, and again
+ // after we load the art.
+ try {
+ await _platform.setMediaItem(
+ SetMediaItemRequest(mediaItem: mediaItem._toMessage()));
+ } catch (e) {
+ _asyncError.add(e);
+ return;
+ }
+ if (operationId != artFetchOperationId) {
+ return;
+ }
+ // Load the art.
+ final loadedFilePath = await _loadArtwork(mediaItem);
+ if (operationId != artFetchOperationId) {
+ return;
+ }
+ // If we successfully downloaded the art, call to platform.
+ if (loadedFilePath != null) {
+ sendToPlatform(loadedFilePath).catchError(_asyncError.add);
+ }
+ }
+ }
+ }
+ });
+ }
+
+ static Future<void> _observeAndroidPlaybackInfo() async {
+ await for (var playbackInfo in _handler.androidPlaybackInfo) {
+ try {
+ await _platform.setAndroidPlaybackInfo(SetAndroidPlaybackInfoRequest(
+ playbackInfo: playbackInfo._toMessage(),
+ ));
+ } catch (e) {
+ _asyncError.add(e);
+ }
+ }
+ }
+
+ static Future<void> _observeQueue() async {
+ await for (var queue in _handler.queue) {
+ if (_config.preloadArtwork) {
+ _loadAllArtwork(queue);
+ }
+ try {
+ await _platform.setQueue(SetQueueRequest(
+ queue: queue.map((item) => item._toMessage()).toList()));
+ } catch (e) {
+ _asyncError.add(e);
+ }
+ }
+ }
+
+ static Future<void> _observePlaybackState() async {
+ var previousState = _handler.playbackState.nvalue;
+ await for (var playbackState in _handler.playbackState) {
+ try {
+ await _platform
+ .setState(SetStateRequest(state: playbackState._toMessage()));
+ if (playbackState.processingState == AudioProcessingState.idle &&
+ previousState?.processingState != AudioProcessingState.idle) {
+ await AudioService._stop();
+ }
+ previousState = playbackState;
+ } catch (e) {
+ _asyncError.add(e);
+ }
+ }
+ }
+
+ /// A stream tracking the current position, suitable for animating a seek bar.
+ /// To ensure a smooth animation, this stream emits values more frequently on
+ /// short media items where the seek bar moves more quickly, and less
+ /// frequenly on long media items where the seek bar moves more slowly. The
+ /// interval between each update will be no quicker than once every 16ms and
+ /// no slower than once every 200ms.
+ ///
+ /// See [createPositionStream] for more control over the stream parameters.
+ static final Stream<Duration> position = createPositionStream(
+ steps: 800,
+ minPeriod: const Duration(milliseconds: 16),
+ maxPeriod: const Duration(milliseconds: 200));
+
+ /// Creates a new stream periodically tracking the current position. The
+ /// stream will aim to emit [steps] position updates at intervals of
+ /// current [MediaItem.duration] / [steps]. This interval will be clipped between [minPeriod]
+ /// and [maxPeriod]. This stream will not emit values while audio playback is
+ /// paused or stalled.
+ ///
+ /// Note: each time this method is called, a new stream is created. If you
+ /// intend to use this stream multiple times, you should hold a reference to
+ /// the returned stream.
+ static Stream<Duration> createPositionStream({
+ int steps = 800,
+ Duration minPeriod = const Duration(milliseconds: 200),
+ Duration maxPeriod = const Duration(milliseconds: 200),
+ }) {
+ assert(minPeriod <= maxPeriod);
+ assert(minPeriod > Duration.zero);
+ Duration? last;
+ late StreamController<Duration> controller;
+ late StreamSubscription<MediaItem?> mediaItemSubscription;
+ late StreamSubscription<PlaybackState> playbackStateSubscription;
+ Timer? currentTimer;
+ Duration duration() => _handler.mediaItem.nvalue?.duration ?? Duration.zero;
+ Duration step() {
+ var s = duration() ~/ steps;
+ if (s < minPeriod) s = minPeriod;
+ if (s > maxPeriod) s = maxPeriod;
+ return s;
+ }
+
+ void yieldPosition(Timer? timer) {
+ if (last != _handler.playbackState.nvalue?.position) {
+ controller.add((last = _handler.playbackState.nvalue?.position)!);
+ }
+ }
+
+ controller = StreamController.broadcast(
+ sync: true,
+ onListen: () {
+ mediaItemSubscription =
+ _handler.mediaItem.listen((MediaItem? mediaItem) {
+ // Potentially a new duration
+ currentTimer?.cancel();
+ currentTimer = Timer.periodic(step(), yieldPosition);
+ });
+ playbackStateSubscription =
+ _handler.playbackState.listen((PlaybackState state) {
+ // Potentially a time discontinuity
+ yieldPosition(currentTimer);
+ });
+ },
+ onCancel: () {
+ mediaItemSubscription.cancel();
+ playbackStateSubscription.cancel();
+ },
+ );
+
+ return controller.stream;
+ }
+
+ /// In Android, forces media button events to be routed to your active media
+ /// session.
+ ///
+ /// This is necessary if you want to play TextToSpeech in the background and
+ /// still respond to media button events. You should call it just before
+ /// playing TextToSpeech.
+ ///
+ /// This is not necessary if you are playing normal audio in the background
+ /// such as music because this kind of "normal" audio playback will
+ /// automatically qualify your app to receive media button events.
+ static Future<void> androidForceEnableMediaButtons() async {
+ await _platform.androidForceEnableMediaButtons(
+ const AndroidForceEnableMediaButtonsRequest(),
+ );
+ }
+
+ /// Stops the service.
+ static Future<void> _stop() async {
+ await _platform.stopService(const StopServiceRequest());
+ }
+
+ static Future<void> _loadAllArtwork(List<MediaItem> queue) async {
+ for (var mediaItem in queue) {
+ await _loadArtwork(mediaItem);
+ }
+ }
+
+ static Future<String?> _loadArtwork(MediaItem mediaItem) async {
+ try {
+ final artUri = mediaItem.artUri;
+ if (artUri != null) {
+ if (artUri.scheme == 'file') {
+ return artUri.toFilePath();
+ } else {
+ final headers = mediaItem.artHeaders;
+ final file = headers != null
+ ? await cacheManager.getSingleFile(mediaItem.artUri!.toString(),
+ headers: headers)
+ : await cacheManager.getSingleFile(mediaItem.artUri!.toString());
+ return file.path;
+ }
+ }
+ } catch (e, st) {
+ // TODO: handle this somehow?
+ // ignore: avoid_print
+ print('Error loading artUri: $e\n$st');
+ }
+ return null;
+ }
+
+ // DEPRECATED members
+
+ /// Deprecated. Use [browsableRootId] instead.
+ @Deprecated("Use browsableRootId instead.")
+ // ignore: constant_identifier_names
+ static const String MEDIA_ROOT_ID = browsableRootId;
+
+ static final _browseMediaChildrenSubject = BehaviorSubject<List<MediaItem>>();
+
+ /// Deprecated. Directly subscribe to a parent's children via
+ /// [AudioHandler.subscribeToChildren].
+ @Deprecated("Use AudioHandler.subscribeToChildren instead.")
+ static Stream<List<MediaItem>> get browseMediaChildrenStream =>
+ _browseMediaChildrenSubject.stream;
+
+ /// Deprecated. Use [AudioHandler.getChildren] instead.
+ @Deprecated("Use AudioHandler.getChildren instead")
+ static List<MediaItem>? get browseMediaChildren =>
+ _browseMediaChildrenSubject.nvalue;
+
+ /// Deprecated. Use [AudioHandler.playbackState] instead.
+ @Deprecated("Use AudioHandler.playbackState instead.")
+ static ValueStream<PlaybackState> get playbackStateStream =>
+ _compatibilitySwitcher.playbackState;
+
+ /// Deprecated. Use [notificationClicked] instead.
+ @Deprecated("Use notificationClicked instead.")
+ static ValueStream<bool> get notificationClickEventStream =>
+ notificationClicked;
+
+ /// Deprecated. Use `value` of [AudioHandler.playbackState] instead.
+ @Deprecated("Use AudioHandler.playbackState.value instead.")
+ static PlaybackState get playbackState =>
+ _compatibilitySwitcher.playbackState.nvalue ?? PlaybackState();
+
+ /// Deprecated. Use [AudioHandler.mediaItem] instead.
+ @Deprecated("Use AudioHandler.mediaItem instead.")
+ static ValueStream<MediaItem?> get currentMediaItemStream =>
+ _compatibilitySwitcher.mediaItem;
+
+ /// Deprecated. Use `value` of [AudioHandler.mediaItem] instead.
+ @Deprecated("Use AudioHandler.mediaItem.value instead.")
+ static MediaItem? get currentMediaItem =>
+ _compatibilitySwitcher.mediaItem.nvalue;
+
+ /// Deprecated. Use [AudioHandler.queue] instead.
+ @Deprecated("Use AudioHandler.queue instead.")
+ static ValueStream<List<MediaItem>?> get queueStream =>
+ _compatibilitySwitcher.queue;
+
+ /// Deprecated. Use `value` of [AudioHandler.queue] instead.
+ @Deprecated("Use AudioHandler.queue.value instead.")
+ static List<MediaItem>? get queue => _compatibilitySwitcher.queue.nvalue;
+
+ /// Deprecated. Use [AudioHandler.customEvent] instead.
+ @Deprecated("Use AudioHandler.customEvent instead.")
+ static Stream<dynamic> get customEventStream =>
+ _compatibilitySwitcher.customEvent;
+
+ /// Deprecated. Use [AudioHandler.playbackState] instead.
+ @Deprecated("Use AudioHandler.playbackState instead.")
+ static ValueStream<bool> get runningStream => playbackStateStream
+ .map((state) => state.processingState != AudioProcessingState.idle)
+ as ValueStream<bool>;
+
+ /// Deprecated. Use [PlaybackState.processingState] of [AudioHandler.playbackState] instead.
+ @Deprecated("Use PlaybackState.processingState instead.")
+ static bool get running => runningStream.nvalue ?? false;
+
+ static StreamSubscription<Map<String, dynamic>>? _childrenSubscription;
+
+ /// Deprecated. The new [AudioHandler] API now automatically starts the
+ /// service when your implementation enters the playing state. Parameters can
+ /// be passed via [AudioHandler.customAction].
+ @Deprecated("Use init instead.")
+ static Future<bool> start({
+ required Function backgroundTaskEntrypoint,
+ Map<String, dynamic>? params,
+ String androidNotificationChannelName = "Notifications",
+ String? androidNotificationChannelDescription,
+ int? androidNotificationColor,
+ String androidNotificationIcon = 'mipmap/ic_launcher',
+ bool androidShowNotificationBadge = false,
+ bool androidNotificationClickStartsActivity = true,
+ bool androidNotificationOngoing = false,
+ bool androidResumeOnClick = true,
+ bool androidStopForegroundOnPause = false,
+ bool androidEnableQueue = false,
+ Size? androidArtDownscaleSize,
+ Duration fastForwardInterval = const Duration(seconds: 10),
+ Duration rewindInterval = const Duration(seconds: 10),
+ }) async {
+ if (!androidEnableQueue) {
+ // ignore: avoid_print
+ print('NOTE: androidEnableQueue is always true from 0.18.0 onwards.');
+ }
+ if (_cacheManager != null && _handler.playbackState.hasValue) {
+ if (_handler.playbackState.nvalue!.processingState !=
+ AudioProcessingState.idle) {
+ return false;
+ }
+ }
+
+ AudioServiceBackground._startCompleter = Completer<BackgroundAudioTask>();
+ backgroundTaskEntrypoint();
+ final task = await AudioServiceBackground._startCompleter!.future;
+ task._handler = _BackgroundAudioHandler();
+ task._handler._task = task;
+ AudioServiceBackground._startCompleter = null;
+
+ if (_cacheManager == null) {
+ _compatibilitySwitcher.inner = task._handler;
+ await init(
+ builder: () => _compatibilitySwitcher,
+ config: AudioServiceConfig(
+ androidResumeOnClick: androidResumeOnClick,
+ androidNotificationChannelName: androidNotificationChannelName,
+ androidNotificationChannelDescription:
+ androidNotificationChannelDescription,
+ notificationColor: androidNotificationColor != null
+ ? Color(androidNotificationColor)
+ : null,
+ androidNotificationIcon: androidNotificationIcon,
+ androidShowNotificationBadge: androidShowNotificationBadge,
+ androidNotificationClickStartsActivity:
+ androidNotificationClickStartsActivity,
+ androidNotificationOngoing: androidNotificationOngoing,
+ androidStopForegroundOnPause: androidStopForegroundOnPause,
+ artDownscaleWidth: androidArtDownscaleSize?.width.round(),
+ artDownscaleHeight: androidArtDownscaleSize?.height.round(),
+ fastForwardInterval: fastForwardInterval,
+ rewindInterval: rewindInterval,
+ ),
+ );
+ } else {
+ _compatibilitySwitcher.inner = task._handler;
+ }
+ await task.onStart(params);
+ return true;
+ }
+
+ /// Deprecated. Instead, subscribe directly to a parent's children via
+ /// [AudioHandler.subscribeToChildren].
+ @Deprecated("Use AudioHandler.subscribeToChildren instead.")
+ static Future<void> setBrowseMediaParent(
+ [String parentMediaId = browsableRootId]) async {
+ _childrenSubscription?.cancel();
+ _childrenSubscription = _compatibilitySwitcher
+ .subscribeToChildren(parentMediaId)
+ .listen((Map<String, dynamic>? options) async {
+ _browseMediaChildrenSubject
+ .add(await _compatibilitySwitcher.getChildren(parentMediaId));
+ });
+ }
+
+ /// Deprecated. Use [AudioHandler.addQueueItem] instead.
+ @Deprecated("Use AudioHandler.addQueueItem instead.")
+ static final addQueueItem = _compatibilitySwitcher.addQueueItem;
+
+ /// Deprecated. Use [AudioHandler.insertQueueItem] instead.
+ @Deprecated("Use AudioHandler.insertQueueItem instead.")
+ static Future<void> addQueueItemAt(MediaItem mediaItem, int index) async {
+ await _compatibilitySwitcher.insertQueueItem(index, mediaItem);
+ }
+
+ /// Deprecated. Use [AudioHandler.removeQueueItem] instead.
+ @Deprecated("Use AudioHandler.removeQueueItem instead.")
+ static final removeQueueItem = _compatibilitySwitcher.removeQueueItem;
+
+ /// Deprecated. Use [AudioHandler.addQueueItems] instead.
+ @Deprecated("Use AudioHandler.addQueueItems instead.")
+ static Future<void> addQueueItems(List<MediaItem> mediaItems) async {
+ for (var mediaItem in mediaItems) {
+ await addQueueItem(mediaItem);
+ }
+ }
+
+ /// Deprecated. Use [AudioHandler.updateQueue] instead.
+ @Deprecated("Use AudioHandler.updateQueue instead.")
+ static final updateQueue = _compatibilitySwitcher.updateQueue;
+
+ /// Deprecated. Use [AudioHandler.updateMediaItem] instead.
+ @Deprecated("Use AudioHandler.updateMediaItem instead.")
+ static final updateMediaItem = _compatibilitySwitcher.updateMediaItem;
+
+ /// Deprecated. Use [AudioHandler.click] instead.
+ @Deprecated("Use AudioHandler.click instead.")
+ static final Future<void> Function([MediaButton]) click =
+ _compatibilitySwitcher.click;
+
+ /// Deprecated. Use [AudioHandler.prepare] instead.
+ @Deprecated("Use AudioHandler.prepare instead.")
+ static final prepare = _compatibilitySwitcher.prepare;
+
+ /// Deprecated. Use [AudioHandler.prepareFromMediaId] instead.
+ @Deprecated("Use AudioHandler.prepareFromMediaId instead.")
+ static final Future<void> Function(String, [Map<String, dynamic>])
+ prepareFromMediaId = _compatibilitySwitcher.prepareFromMediaId;
+
+ /// Deprecated. Use [AudioHandler.play] instead.
+ @Deprecated("Use AudioHandler.play instead.")
+ static final play = _compatibilitySwitcher.play;
+
+ /// Deprecated. Use [AudioHandler.playFromMediaId] instead.
+ @Deprecated("Use AudioHandler.playFromMediaId instead.")
+ static final Future<void> Function(String, [Map<String, dynamic>])
+ playFromMediaId = _compatibilitySwitcher.playFromMediaId;
+
+ /// Deprecated. Use [AudioHandler.playMediaItem] instead.
+ @Deprecated("Use AudioHandler.playMediaItem instead.")
+ static final playMediaItem = _compatibilitySwitcher.playMediaItem;
+
+ /// Deprecated. Use [AudioHandler.skipToQueueItem] instead.
+ @Deprecated("Use AudioHandler.skipToQueueItem instead.")
+ static Future<void> skipToQueueItem(String mediaId) async {
+ final queue = _compatibilitySwitcher.queue.nvalue!;
+ final index = queue.indexWhere((item) => item.id == mediaId);
+ await _compatibilitySwitcher.skipToQueueItem(index);
+ }
+
+ /// Deprecated. Use [AudioHandler.pause] instead.
+ @Deprecated("Use AudioHandler.pause instead.")
+ static final pause = _compatibilitySwitcher.pause;
+
+ /// Deprecated. Use [AudioHandler.stop] instead.
+ @Deprecated("Use AudioHandler.stop instead.")
+ static final stop = _compatibilitySwitcher.stop;
+
+ /// Deprecated. Use [AudioHandler.seek] instead.
+ @Deprecated("Use AudioHandler.seek instead.")
+ static final seekTo = _compatibilitySwitcher.seek;
+
+ /// Deprecated. Use [AudioHandler.skipToNext] instead.
+ @Deprecated("Use AudioHandler.skipToNext instead.")
+ static final skipToNext = _compatibilitySwitcher.skipToNext;
+
+ /// Deprecated. Use [AudioHandler.skipToPrevious] instead.
+ @Deprecated("Use AudioHandler.skipToPrevious instead.")
+ static final skipToPrevious = _compatibilitySwitcher.skipToPrevious;
+
+ /// Deprecated. Use [AudioHandler.fastForward] instead.
+ @Deprecated("Use AudioHandler.fastForward instead.")
+ static final Future<void> Function() fastForward =
+ _compatibilitySwitcher.fastForward;
+
+ /// Deprecated. Use [AudioHandler.rewind] instead.
+ @Deprecated("Use AudioHandler.rewind instead.")
+ static final Future<void> Function() rewind = _compatibilitySwitcher.rewind;
+
+ /// Deprecated. Use [AudioHandler.setRepeatMode] instead.
+ @Deprecated("Use AudioHandler.setRepeatMode instead.")
+ static final setRepeatMode = _compatibilitySwitcher.setRepeatMode;
+
+ /// Deprecated. Use [AudioHandler.setShuffleMode] instead.
+ @Deprecated("Use AudioHandler.setShuffleMode instead.")
+ static final setShuffleMode = _compatibilitySwitcher.setShuffleMode;
+
+ /// Deprecated. Use [AudioHandler.setRating] instead.
+ @Deprecated("Use AudioHandler.setRating instead.")
+ static Future<void> setRating(Rating rating, Map<dynamic, dynamic> extras) =>
+ _compatibilitySwitcher.setRating(rating, extras.cast<String, dynamic>());
+
+ /// Deprecated. Use [AudioHandler.setSpeed] instead.
+ @Deprecated("Use AudioHandler.setSpeed instead.")
+ static final setSpeed = _compatibilitySwitcher.setSpeed;
+
+ /// Deprecated. Use [AudioHandler.seekBackward] instead.
+ @Deprecated("Use audioHandler.seekBackward instead.")
+ static final seekBackward = _compatibilitySwitcher.seekBackward;
+
+ /// Deprecated. Use [AudioHandler.seekForward] instead.
+ @Deprecated("Use AudioHandler.seekForward instead.")
+ static final seekForward = _compatibilitySwitcher.seekForward;
+
+ /// Deprecated. Use [AudioHandler.customAction] instead.
+ @Deprecated("Use AudioHandler.customAction instead.")
+ static final Future<dynamic> Function(String, Map<String, dynamic>)
+ customAction = _compatibilitySwitcher.customAction;
+
+ /// Deprecated. Use [position] instead.
+ @Deprecated("Use position instead.")
+ static final ValueStream<Duration> positionStream =
+ BehaviorSubject.seeded(Duration.zero, sync: true)
+ ..addStream(position)
+ ..stream;
+}
+
+class _BackgroundAudioHandler extends BaseAudioHandler {
+ // ignore: deprecated_member_use_from_same_package
+ late BackgroundAudioTask _task;
+
+ @override
+ // ignore: deprecated_member_use_from_same_package
+ Future<void> prepare() => _task.onPrepare();
+
+ @override
+ Future<void> prepareFromMediaId(String mediaId,
+ [Map<String, dynamic>? extras]) =>
+ // ignore: deprecated_member_use_from_same_package
+ _task.onPrepareFromMediaId(mediaId);
+
+ @override
+ // ignore: deprecated_member_use_from_same_package
+ Future<void> play() => _task.onPlay();
+
+ @override
+ Future<void> playFromMediaId(String mediaId,
+ [Map<String, dynamic>? extras]) =>
+ // ignore: deprecated_member_use_from_same_package
+ _task.onPlayFromMediaId(mediaId);
+
+ @override
+ Future<void> playMediaItem(MediaItem mediaItem) =>
+ // ignore: deprecated_member_use_from_same_package
+ _task.onPlayMediaItem(mediaItem);
+
+ @override
+ // ignore: deprecated_member_use_from_same_package
+ Future<void> pause() => _task.onPause();
+
+ @override
+ Future<void> click([MediaButton button = MediaButton.media]) =>
+ // ignore: deprecated_member_use_from_same_package
+ _task.onClick(button);
+
+ @override
+ // ignore: deprecated_member_use_from_same_package
+ Future<void> stop() => _task.onStop();
+
+ @override
+ Future<void> addQueueItem(MediaItem mediaItem) =>
+ // ignore: deprecated_member_use_from_same_package
+ _task.onAddQueueItem(mediaItem);
+
+ @override
+ Future<void> addQueueItems(List<MediaItem> mediaItems) async {
+ for (var mediaItem in mediaItems) {
+ // ignore: deprecated_member_use_from_same_package
+ await _task.onAddQueueItem(mediaItem);
+ }
+ }
+
+ @override
+ Future<void> insertQueueItem(int index, MediaItem mediaItem) =>
+ // ignore: deprecated_member_use_from_same_package
+ _task.onAddQueueItemAt(mediaItem, index);
+
+ @override
+ // ignore: deprecated_member_use_from_same_package
+ Future<void> updateQueue(List<MediaItem> queue) => _task.onUpdateQueue(queue);
+
+ @override
+ Future<void> updateMediaItem(MediaItem mediaItem) =>
+ // ignore: deprecated_member_use_from_same_package
+ _task.onUpdateMediaItem(mediaItem);
+
+ @override
+ Future<void> removeQueueItem(MediaItem mediaItem) =>
+ // ignore: deprecated_member_use_from_same_package
+ _task.onRemoveQueueItem(mediaItem);
+
+ @override
+ // ignore: deprecated_member_use_from_same_package
+ Future<void> skipToNext() => _task.onSkipToNext();
+
+ @override
+ // ignore: deprecated_member_use_from_same_package
+ Future<void> skipToPrevious() => _task.onSkipToPrevious();
+
+ @override
+ // ignore: deprecated_member_use_from_same_package
+ Future<void> fastForward() => _task.onFastForward();
+
+ @override
+ // ignore: deprecated_member_use_from_same_package
+ Future<void> rewind() => _task.onRewind();
+
+ @override
+ Future<void> skipToQueueItem(int index) async {
+ final queue = this.queue.nvalue ?? <MediaItem>[];
+ if (index < 0 || index >= queue.length) return;
+ final mediaItem = queue[index];
+ // ignore: deprecated_member_use_from_same_package
+ await _task.onSkipToQueueItem(mediaItem.id);
+ }
+
+ @override
+ // ignore: deprecated_member_use_from_same_package
+ Future<void> seek(Duration position) => _task.onSeekTo(position);
+
+ @override
+ Future<void> setRating(Rating rating, [Map<String, dynamic>? extras]) =>
+ // ignore: deprecated_member_use_from_same_package
+ _task.onSetRating(rating, extras);
+
+ @override
+ Future<void> setRepeatMode(AudioServiceRepeatMode repeatMode) =>
+ // ignore: deprecated_member_use_from_same_package
+ _task.onSetRepeatMode(repeatMode);
+
+ @override
+ Future<void> setShuffleMode(AudioServiceShuffleMode shuffleMode) =>
+ // ignore: deprecated_member_use_from_same_package
+ _task.onSetShuffleMode(shuffleMode);
+
+ @override
+ // ignore: deprecated_member_use_from_same_package
+ Future<void> seekBackward(bool begin) => _task.onSeekBackward(begin);
+
+ @override
+ // ignore: deprecated_member_use_from_same_package
+ Future<void> seekForward(bool begin) => _task.onSeekForward(begin);
+
+ @override
+ // ignore: deprecated_member_use_from_same_package
+ Future<void> setSpeed(double speed) => _task.onSetSpeed(speed);
+
+ @override
+ Future<dynamic> customAction(String name, [Map<String, dynamic>? extras]) =>
+ // ignore: deprecated_member_use_from_same_package
+ _task.onCustomAction(name, extras);
+
+ @override
+ // ignore: deprecated_member_use_from_same_package
+ Future<void> onNotificationDeleted() => _task.onClose();
+
+ @override
+ Future<List<MediaItem>> getChildren(String parentMediaId,
+ [Map<String, dynamic>? options]) =>
+ // ignore: deprecated_member_use_from_same_package
+ _task.onLoadChildren(parentMediaId);
+}
+
+/// This class is deprecated. Use [BaseAudioHandler] instead.
+@Deprecated("Use AudioHandler instead.")
+abstract class BackgroundAudioTask {
+ late _BackgroundAudioHandler _handler;
+
+ /// Deprecated. Use [AudioServiceConfig.fastForwardInterval] from [AudioService.config] instead.
+ @Deprecated(
+ "Use [AudioServiceConfig.fastForwardInterval] from [AudioService.config] instead.")
+ Duration get fastForwardInterval => AudioService.config.fastForwardInterval;
+
+ /// Deprecated. Use [AudioServiceConfig.rewindInterval] from [AudioService.config] instead.
+ @Deprecated(
+ "Use [AudioServiceConfig.rewindInterval] from [AudioService.config] instead.")
+ Duration get rewindInterval => AudioService.config.rewindInterval;
+
+ /// Deprecated. The new [AudioHandler] API now automatically starts the
+ /// service when your implementation enters the playing state. Parameters can
+ /// be passed via [AudioHandler.customAction].
+ @Deprecated("Use AudioService.init instead.")
+ Future<void> onStart(Map<String, dynamic>? params) async {}
+
+ /// Deprecated. Replaced by [AudioHandler.stop].
+ @mustCallSuper
+ @Deprecated("Use AudioHandler.stop instead.")
+ Future<void> onStop() async {
+ final audioSession = await AudioSession.instance;
+ try {
+ await audioSession.setActive(false);
+ } catch (e) {
+ // ignore: avoid_print
+ print("While deactivating audio session: $e");
+ }
+ }
+
+ /// Deprecated. Replaced by [AudioHandler.getChildren].
+ @Deprecated("Use AudioHandler.getChildren instead.")
+ Future<List<MediaItem>> onLoadChildren(String parentMediaId) async => [];
+
+ /// Deprecated. Replaced by [AudioHandler.click].
+ @Deprecated("Use AudioHandler.click instead.")
+ Future<void> onClick(MediaButton? button) async {
+ switch (button!) {
+ case MediaButton.media:
+ if (_handler.playbackState.nvalue!.playing) {
+ await onPause();
+ } else {
+ await onPlay();
+ }
+ break;
+ case MediaButton.next:
+ await onSkipToNext();
+ break;
+ case MediaButton.previous:
+ await onSkipToPrevious();
+ break;
+ }
+ }
+
+ /// Deprecated. Replaced by [AudioHandler.pause].
+ @Deprecated("Use AudioHandler.pause instead.")
+ Future<void> onPause() async {}
+
+ /// Deprecated. Replaced by [AudioHandler.prepare].
+ @Deprecated("Use AudioHandler.prepare instead.")
+ Future<void> onPrepare() async {}
+
+ /// Deprecated. Replaced by [AudioHandler.prepareFromMediaId].
+ @Deprecated("Use AudioHandler.prepareFromMediaId instead.")
+ Future<void> onPrepareFromMediaId(String mediaId) async {}
+
+ /// Deprecated. Replaced by [AudioHandler.play].
+ @Deprecated("Use AudioHandler.play instead.")
+ Future<void> onPlay() async {}
+
+ /// Deprecated. Replaced by [AudioHandler.playFromMediaId].
+ @Deprecated("Use AudioHandler.playFromMediaId instead.")
+ Future<void> onPlayFromMediaId(String mediaId) async {}
+
+ /// Deprecated. Replaced by [AudioHandler.playMediaItem].
+ @Deprecated("Use AudioHandler.playMediaItem instead.")
+ Future<void> onPlayMediaItem(MediaItem mediaItem) async {}
+
+ /// Deprecated. Replaced by [AudioHandler.addQueueItem].
+ @Deprecated("Use AudioHandler.addQueueItem instead.")
+ Future<void> onAddQueueItem(MediaItem mediaItem) async {}
+
+ /// Deprecated. Replaced by [AudioHandler.updateQueue].
+ @Deprecated("Use AudioHandler.updateQueue instead.")
+ Future<void> onUpdateQueue(List<MediaItem> queue) async {}
+
+ /// Deprecated. Replaced by [AudioHandler.updateMediaItem].
+ @Deprecated("Use AudioHandler.updateMediaItem instead.")
+ Future<void> onUpdateMediaItem(MediaItem mediaItem) async {}
+
+ /// Deprecated. Replaced by [AudioHandler.insertQueueItem].
+ @Deprecated("Use AudioHandler.insertQueueItem instead.")
+ Future<void> onAddQueueItemAt(MediaItem mediaItem, int index) async {}
+
+ /// Deprecated. Replaced by [AudioHandler.removeQueueItem].
+ @Deprecated("Use AudioHandler.removeQueueItem instead.")
+ Future<void> onRemoveQueueItem(MediaItem mediaItem) async {}
+
+ /// Deprecated. Replaced by [AudioHandler.skipToNext].
+ @Deprecated("Use AudioHandler.skipToNext instead.")
+ Future<void> onSkipToNext() => _skip(1);
+
+ /// Deprecated. Replaced by [AudioHandler.skipToPrevious].
+ @Deprecated("Use AudioHandler.skipToPrevious instead.")
+ Future<void> onSkipToPrevious() => _skip(-1);
+
+ /// Deprecated. Replaced by [AudioHandler.fastForward].
+ @Deprecated("Use AudioHandler.fastForward instead.")
+ Future<void> onFastForward() async {}
+
+ /// Deprecated. Replaced by [AudioHandler.rewind].
+ @Deprecated("Use AudioHandler.rewind instead.")
+ Future<void> onRewind() async {}
+
+ /// Deprecated. Replaced by [AudioHandler.skipToQueueItem].
+ @Deprecated("Use AudioHandler.skipToQueueItem instead.")
+ Future<void> onSkipToQueueItem(String mediaId) async {}
+
+ /// Deprecated. Replaced by [AudioHandler.seek].
+ @Deprecated("Use AudioHandler.seek instead.")
+ Future<void> onSeekTo(Duration position) async {}
+
+ /// Deprecated. Replaced by [AudioHandler.setRating].
+ @Deprecated("Use AudioHandler.setRating instead.")
+ Future<void> onSetRating(Rating rating, Map<String, dynamic>? extras) async {}
+
+ /// Deprecated. Replaced by [AudioHandler.setRepeatMode].
+ @Deprecated("Use AudioHandler.setRepeatMode instead.")
+ Future<void> onSetRepeatMode(AudioServiceRepeatMode repeatMode) async {}
+
+ /// Deprecated. Replaced by [AudioHandler.setShuffleMode].
+ @Deprecated("Use AudioHandler.setShuffleMode instead.")
+ Future<void> onSetShuffleMode(AudioServiceShuffleMode shuffleMode) async {}
+
+ /// Deprecated. Replaced by [AudioHandler.seekBackward].
+ @Deprecated("Use AudioHandler.seekBackward instead.")
+ Future<void> onSeekBackward(bool begin) async {}
+
+ /// Deprecated. Replaced by [AudioHandler.seekForward].
+ @Deprecated("Use AudioHandler.seekForward instead.")
+ Future<void> onSeekForward(bool begin) async {}
+
+ /// Deprecated. Replaced by [AudioHandler.setSpeed].
+ @Deprecated("Use AudioHandler.setSpeed instead.")
+ Future<void> onSetSpeed(double speed) async {}
+
+ /// Deprecated. Replaced by [AudioHandler.customAction].
+ @Deprecated("Use AudioHandler.customAction instead.")
+ Future<dynamic> onCustomAction(String name, dynamic arguments) async {}
+
+ /// Deprecated. Replaced by [AudioHandler.onTaskRemoved].
+ @Deprecated("Use AudioHandler.onTaskRemoved instead.")
+ Future<void> onTaskRemoved() async {}
+
+ /// Deprecated. Replaced by [AudioHandler.onNotificationDeleted].
+ @Deprecated("Use AudioHandler.onNotificationDeleted instead.")
+ Future<void> onClose() => onStop();
+
+ Future<void> _skip(int offset) async {
+ final mediaItem = _handler.mediaItem.nvalue;
+ if (mediaItem == null) return;
+ final queue = _handler.queue.nvalue ?? <MediaItem>[];
+ final i = queue.indexOf(mediaItem);
+ if (i == -1) return;
+ final newIndex = i + offset;
+ if (newIndex >= 0 && newIndex < queue.length) {
+ await onSkipToQueueItem(queue[newIndex].id);
+ }
+ }
+}
+
+/// An [AudioHandler] plays audio, provides state updates and query results to
+/// clients. It implements standard protocols that allow it to be remotely
+/// controlled by the lock screen, media notifications, the iOS control center,
+/// headsets, smart watches, car audio systems, and other compatible agents.
+///
+/// This class cannot be subclassed directly. Implementations should subclass
+/// [BaseAudioHandler], and composite behaviours should be defined as subclasses
+/// of [CompositeAudioHandler].
+abstract class AudioHandler {
+ AudioHandler._();
+
+ /// Prepare media items for playback.
+ Future<void> prepare();
+
+ /// Prepare a specific media item for playback.
+ Future<void> prepareFromMediaId(String mediaId,
+ [Map<String, dynamic>? extras]);
+
+ /// Prepare playback from a search query.
+ Future<void> prepareFromSearch(String query, [Map<String, dynamic>? extras]);
+
+ /// Prepare a media item represented by a Uri for playback.
+ Future<void> prepareFromUri(Uri uri, [Map<String, dynamic>? extras]);
+
+ /// Start or resume playback.
+ Future<void> play();
+
+ /// Play a specific media item.
+ Future<void> playFromMediaId(String mediaId, [Map<String, dynamic>? extras]);
+
+ /// Begin playback from a search query.
+ Future<void> playFromSearch(String query, [Map<String, dynamic>? extras]);
+
+ /// Play a media item represented by a Uri.
+ Future<void> playFromUri(Uri uri, [Map<String, dynamic>? extras]);
+
+ /// Play a specific media item.
+ Future<void> playMediaItem(MediaItem mediaItem);
+
+ /// Pause playback.
+ Future<void> pause();
+
+ /// Process a headset button click, where [button] defaults to
+ /// [MediaButton.media].
+ Future<void> click([MediaButton button = MediaButton.media]);
+
+ /// Stop playback and release resources.
+ Future<void> stop();
+
+ /// Add [mediaItem] to the queue.
+ Future<void> addQueueItem(MediaItem mediaItem);
+
+ /// Add [mediaItems] to the queue.
+ Future<void> addQueueItems(List<MediaItem> mediaItems);
+
+ /// Insert [mediaItem] into the queue at position [index].
+ Future<void> insertQueueItem(int index, MediaItem mediaItem);
+
+ /// Update to the queue to [queue].
+ Future<void> updateQueue(List<MediaItem> queue);
+
+ /// Update the properties of [mediaItem].
+ Future<void> updateMediaItem(MediaItem mediaItem);
+
+ /// Remove [mediaItem] from the queue.
+ Future<void> removeQueueItem(MediaItem mediaItem);
+
+ /// Remove media item from the queue at the specified [index].
+ Future<void> removeQueueItemAt(int index);
+
+ /// Skip to the next item in the queue.
+ Future<void> skipToNext();
+
+ /// Skip to the previous item in the queue.
+ Future<void> skipToPrevious();
+
+ /// Jump forward by [AudioServiceConfig.fastForwardInterval].
+ Future<void> fastForward();
+
+ /// Jump backward by [AudioServiceConfig.rewindInterval]. Note: this value
+ /// must be positive.
+ Future<void> rewind();
+
+ /// Skip to a queue item.
+ Future<void> skipToQueueItem(int index);
+
+ /// Seek to [position].
+ Future<void> seek(Duration position);
+
+ /// Set the rating.
+ Future<void> setRating(Rating rating, [Map<String, dynamic>? extras]);
+
+ /// Set whether captioning is enabled.
+ Future<void> setCaptioningEnabled(bool enabled);
+
+ /// Set the repeat mode.
+ Future<void> setRepeatMode(AudioServiceRepeatMode repeatMode);
+
+ /// Set the shuffle mode.
+ Future<void> setShuffleMode(AudioServiceShuffleMode shuffleMode);
+
+ /// Begin or end seeking backward continuously.
+ Future<void> seekBackward(bool begin);
+
+ /// Begin or end seeking forward continuously.
+ Future<void> seekForward(bool begin);
+
+ /// Set the playback speed.
+ Future<void> setSpeed(double speed);
+
+ /// A mechanism to support app-specific actions.
+ Future<dynamic> customAction(String name, [Map<String, dynamic>? extras]);
+
+ /// Handle the task being swiped away in the task manager (Android).
+ Future<void> onTaskRemoved();
+
+ /// Handle the notification being swiped away (Android).
+ Future<void> onNotificationDeleted();
+
+ /// Get the children of a parent media item.
+ Future<List<MediaItem>> getChildren(String parentMediaId,
+ [Map<String, dynamic>? options]);
+
+ /// Get a value stream that emits service-specific options to send to the
+ /// client whenever the children under the specified parent change. The
+ /// emitted options may contain information about what changed. A client that
+ /// is subscribed to this stream should call [getChildren] to obtain the
+ /// changed children.
+ ValueStream<Map<String, dynamic>> subscribeToChildren(String parentMediaId);
+
+ /// Get a particular media item.
+ Future<MediaItem?> getMediaItem(String mediaId);
+
+ /// Search for media items.
+ Future<List<MediaItem>> search(String query, [Map<String, dynamic>? extras]);
+
+ /// Set the remote volume on Android. This works only when using
+ /// [RemoteAndroidPlaybackInfo].
+ Future<void> androidSetRemoteVolume(int volumeIndex);
+
+ /// Adjust the remote volume on Android. This works only when using
+ /// [RemoteAndroidPlaybackInfo].
+ Future<void> androidAdjustRemoteVolume(AndroidVolumeDirection direction);
+
+ /// A value stream of playback states.
+ ValueStream<PlaybackState> get playbackState;
+
+ /// A value stream of the current queue.
+ ValueStream<List<MediaItem>> get queue;
+
+ /// A value stream of the current queueTitle.
+ ValueStream<String> get queueTitle;
+
+ /// A value stream of the current media item.
+ ValueStream<MediaItem?> get mediaItem;
+
+ /// A value stream of the current rating style.
+ ValueStream<RatingStyle> get ratingStyle;
+
+ /// A value stream of the current [AndroidPlaybackInfo].
+ ValueStream<AndroidPlaybackInfo> get androidPlaybackInfo;
+
+ /// A stream of custom events.
+ Stream<dynamic> get customEvent;
+
+ /// A stream of custom states.
+ ValueStream<dynamic> get customState;
+}
+
+/// A [SwitchAudioHandler] wraps another [AudioHandler] that may be switched for
+/// another at any time by setting [inner].
+class SwitchAudioHandler extends CompositeAudioHandler {
+ final BehaviorSubject<PlaybackState> _playbackState = BehaviorSubject();
+ final BehaviorSubject<List<MediaItem>> _queue = BehaviorSubject();
+ final BehaviorSubject<String> _queueTitle = BehaviorSubject();
+ final BehaviorSubject<MediaItem?> _mediaItem = BehaviorSubject();
+ final BehaviorSubject<AndroidPlaybackInfo> _androidPlaybackInfo =
+ BehaviorSubject();
+ final BehaviorSubject<RatingStyle> _ratingStyle = BehaviorSubject();
+ final PublishSubject<dynamic> _customEvent = PublishSubject<dynamic>();
+ final BehaviorSubject<dynamic> _customState = BehaviorSubject<dynamic>();
+
+ @override
+ ValueStream<PlaybackState> get playbackState => _playbackState;
+
+ @override
+ ValueStream<List<MediaItem>> get queue => _queue;
+
+ @override
+ ValueStream<String> get queueTitle => _queueTitle;
+
+ @override
+ ValueStream<MediaItem?> get mediaItem => _mediaItem;
+
+ @override
+ ValueStream<AndroidPlaybackInfo> get androidPlaybackInfo =>
+ _androidPlaybackInfo;
+
+ @override
+ ValueStream<RatingStyle> get ratingStyle => _ratingStyle;
+
+ @override
+ Stream<dynamic> get customEvent => _customEvent;
+
+ @override
+ ValueStream<dynamic> get customState => _customState;
+
+ StreamSubscription<PlaybackState>? _playbackStateSubscription;
+ StreamSubscription<List<MediaItem>>? _queueSubscription;
+ StreamSubscription<String>? _queueTitleSubscription;
+ StreamSubscription<MediaItem?>? _mediaItemSubscription;
+ StreamSubscription<AndroidPlaybackInfo>? _androidPlaybackInfoSubscription;
+ StreamSubscription<RatingStyle>? _ratingStyleSubscription;
+ StreamSubscription<dynamic>? _customEventSubscription;
+ StreamSubscription<dynamic>? _customStateSubscription;
+
+ /// Creates a [SwitchAudioHandler] with an initial [inner] handler, which
+ /// defaults to a no-op handler.
+ SwitchAudioHandler([AudioHandler? inner])
+ : this._(inner ?? BaseAudioHandler());
+
+ SwitchAudioHandler._(AudioHandler inner) : super(inner) {
+ this.inner = inner;
+ }
+
+ /// The current inner [AudioHandler] that this [SwitchAudioHandler] will
+ /// delegate to.
+ AudioHandler get inner => _inner;
+
+ set inner(AudioHandler newInner) {
+ // Should disallow all ancestors...
+ assert(newInner != this);
+ _playbackStateSubscription?.cancel();
+ _queueSubscription?.cancel();
+ _queueTitleSubscription?.cancel();
+ _mediaItemSubscription?.cancel();
+ _androidPlaybackInfoSubscription?.cancel();
+ _ratingStyleSubscription?.cancel();
+ _customEventSubscription?.cancel();
+ _customStateSubscription?.cancel();
+ _inner = newInner;
+ _playbackStateSubscription = inner.playbackState.listen(_playbackState.add);
+ _queueSubscription = inner.queue.listen(_queue.add);
+ _queueTitleSubscription = inner.queueTitle.listen(_queueTitle.add);
+ // XXX: This only works in one direction.
+ _mediaItemSubscription = inner.mediaItem.listen(_mediaItem.add);
+ _androidPlaybackInfoSubscription =
+ inner.androidPlaybackInfo.listen(_androidPlaybackInfo.add);
+ _ratingStyleSubscription = inner.ratingStyle.listen(_ratingStyle.add);
+ _customEventSubscription = inner.customEvent.listen(_customEvent.add);
+ _customStateSubscription = inner.customState.listen(_customState.add);
+ }
+}
+
+/// A [CompositeAudioHandler] wraps another [AudioHandler] and adds additional
+/// behaviour to it. Each method will by default pass through to the
+/// corresponding method of the wrapped handler. If you override a method, it
+/// must call super in addition to any "additional" functionality you add.
+class CompositeAudioHandler extends AudioHandler {
+ AudioHandler _inner;
+
+ /// Create the [CompositeAudioHandler] with the given wrapped handler.
+ CompositeAudioHandler(AudioHandler inner)
+ : _inner = inner,
+ super._();
+
+ @override
+ @mustCallSuper
+ Future<void> prepare() => _inner.prepare();
+
+ @override
+ @mustCallSuper
+ Future<void> prepareFromMediaId(String mediaId,
+ [Map<String, dynamic>? extras]) =>
+ _inner.prepareFromMediaId(mediaId, extras);
+
+ @override
+ @mustCallSuper
+ Future<void> prepareFromSearch(String query,
+ [Map<String, dynamic>? extras]) =>
+ _inner.prepareFromSearch(query, extras);
+
+ @override
+ @mustCallSuper
+ Future<void> prepareFromUri(Uri uri, [Map<String, dynamic>? extras]) =>
+ _inner.prepareFromUri(uri, extras);
+
+ @override
+ @mustCallSuper
+ Future<void> play() => _inner.play();
+
+ @override
+ @mustCallSuper
+ Future<void> playFromMediaId(String mediaId,
+ [Map<String, dynamic>? extras]) =>
+ _inner.playFromMediaId(mediaId, extras);
+
+ @override
+ @mustCallSuper
+ Future<void> playFromSearch(String query, [Map<String, dynamic>? extras]) =>
+ _inner.playFromSearch(query, extras);
+
+ @override
+ @mustCallSuper
+ Future<void> playFromUri(Uri uri, [Map<String, dynamic>? extras]) =>
+ _inner.playFromUri(uri, extras);
+
+ @override
+ @mustCallSuper
+ Future<void> playMediaItem(MediaItem mediaItem) =>
+ _inner.playMediaItem(mediaItem);
+
+ @override
+ @mustCallSuper
+ Future<void> pause() => _inner.pause();
+
+ @override
+ @mustCallSuper
+ Future<void> click([MediaButton button = MediaButton.media]) =>
+ _inner.click(button);
+
+ @override
+ @mustCallSuper
+ Future<void> stop() => _inner.stop();
+
+ @override
+ @mustCallSuper
+ Future<void> addQueueItem(MediaItem mediaItem) =>
+ _inner.addQueueItem(mediaItem);
+
+ @override
+ @mustCallSuper
+ Future<void> addQueueItems(List<MediaItem> mediaItems) =>
+ _inner.addQueueItems(mediaItems);
+
+ @override
+ @mustCallSuper
+ Future<void> insertQueueItem(int index, MediaItem mediaItem) =>
+ _inner.insertQueueItem(index, mediaItem);
+
+ @override
+ @mustCallSuper
+ Future<void> updateQueue(List<MediaItem> queue) => _inner.updateQueue(queue);
+
+ @override
+ @mustCallSuper
+ Future<void> updateMediaItem(MediaItem mediaItem) =>
+ _inner.updateMediaItem(mediaItem);
+
+ @override
+ @mustCallSuper
+ Future<void> removeQueueItem(MediaItem mediaItem) =>
+ _inner.removeQueueItem(mediaItem);
+
+ @override
+ @mustCallSuper
+ Future<void> removeQueueItemAt(int index) => _inner.removeQueueItemAt(index);
+
+ @override
+ @mustCallSuper
+ Future<void> skipToNext() => _inner.skipToNext();
+
+ @override
+ @mustCallSuper
+ Future<void> skipToPrevious() => _inner.skipToPrevious();
+
+ @override
+ @mustCallSuper
+ Future<void> fastForward() => _inner.fastForward();
+
+ @override
+ @mustCallSuper
+ Future<void> rewind() => _inner.rewind();
+
+ @override
+ @mustCallSuper
+ Future<void> skipToQueueItem(int index) => _inner.skipToQueueItem(index);
+
+ @override
+ @mustCallSuper
+ Future<void> seek(Duration position) => _inner.seek(position);
+
+ @override
+ @mustCallSuper
+ Future<void> setRating(Rating rating, [Map<String, dynamic>? extras]) =>
+ _inner.setRating(rating, extras);
+
+ @override
+ @mustCallSuper
+ Future<void> setCaptioningEnabled(bool enabled) =>
+ _inner.setCaptioningEnabled(enabled);
+
+ @override
+ @mustCallSuper
+ Future<void> setRepeatMode(AudioServiceRepeatMode repeatMode) =>
+ _inner.setRepeatMode(repeatMode);
+
+ @override
+ @mustCallSuper
+ Future<void> setShuffleMode(AudioServiceShuffleMode shuffleMode) =>
+ _inner.setShuffleMode(shuffleMode);
+
+ @override
+ @mustCallSuper
+ Future<void> seekBackward(bool begin) => _inner.seekBackward(begin);
+
+ @override
+ @mustCallSuper
+ Future<void> seekForward(bool begin) => _inner.seekForward(begin);
+
+ @override
+ @mustCallSuper
+ Future<void> setSpeed(double speed) => _inner.setSpeed(speed);
+
+ @override
+ @mustCallSuper
+ Future<dynamic> customAction(String name, [Map<String, dynamic>? extras]) =>
+ _inner.customAction(name, extras);
+
+ @override
+ @mustCallSuper
+ Future<void> onTaskRemoved() => _inner.onTaskRemoved();
+
+ @override
+ @mustCallSuper
+ Future<void> onNotificationDeleted() => _inner.onNotificationDeleted();
+
+ @override
+ @mustCallSuper
+ Future<List<MediaItem>> getChildren(String parentMediaId,
+ [Map<String, dynamic>? options]) =>
+ _inner.getChildren(parentMediaId, options);
+
+ @override
+ @mustCallSuper
+ ValueStream<Map<String, dynamic>> subscribeToChildren(String parentMediaId) =>
+ _inner.subscribeToChildren(parentMediaId);
+
+ @override
+ @mustCallSuper
+ Future<MediaItem?> getMediaItem(String mediaId) =>
+ _inner.getMediaItem(mediaId);
+
+ @override
+ @mustCallSuper
+ Future<List<MediaItem>> search(String query,
+ [Map<String, dynamic>? extras]) =>
+ _inner.search(query, extras);
+
+ @override
+ @mustCallSuper
+ Future<void> androidSetRemoteVolume(int volumeIndex) =>
+ _inner.androidSetRemoteVolume(volumeIndex);
+
+ @override
+ @mustCallSuper
+ Future<void> androidAdjustRemoteVolume(AndroidVolumeDirection direction) =>
+ _inner.androidAdjustRemoteVolume(direction);
+
+ @override
+ ValueStream<PlaybackState> get playbackState => _inner.playbackState;
+
+ @override
+ ValueStream<List<MediaItem>> get queue => _inner.queue;
+
+ @override
+ ValueStream<String> get queueTitle => _inner.queueTitle;
+
+ @override
+ ValueStream<MediaItem?> get mediaItem => _inner.mediaItem;
+
+ @override
+ ValueStream<RatingStyle> get ratingStyle => _inner.ratingStyle;
+
+ @override
+ ValueStream<AndroidPlaybackInfo> get androidPlaybackInfo =>
+ _inner.androidPlaybackInfo;
+
+ @override
+ Stream<dynamic> get customEvent => _inner.customEvent;
+
+ @override
+ ValueStream<dynamic> get customState => _inner.customState;
+}
+
+class _IsolateRequest {
+ /// The send port for sending the response of this request.
+ final SendPort sendPort;
+ final String method;
+ final List<dynamic>? arguments;
+
+ _IsolateRequest(this.sendPort, this.method, [this.arguments]);
+}
+
+/// A [CompositeAudioHandler] that can be accessed from other isolates via
+/// [lookup].
+///
+/// This handler recognises the custom action 'unregister' so that
+/// `customAction('unregister')` can be called from a client to unregister this
+/// handler, or it can be unregistered by a direct invocation of [unregister].
+class IsolatedAudioHandler extends CompositeAudioHandler {
+ /// The default port name by which this isolated audio handler can be looked
+ /// up.
+ static const defaultPortName = 'com.ryanheise.audioservice.port';
+
+ /// Connect to an [IsolatedAudioHandler] from another isolate having the name
+ /// [portName] (defaulting to [defaultPortName]).
+ static Future<AudioHandler> lookup(
+ {String portName = defaultPortName}) async {
+ assert(!kIsWeb, "Isolates are not supported on web");
+ final handler = _ClientIsolatedAudioHandler(portName: portName);
+ await handler._init();
+ return handler;
+ }
+
+ /// The port name to use when looking up this handler.
+ final String portName;
+
+ final _receivePort = ReceivePort();
+
+ /// Creates an [IsolatedAudioHandler] that can be looked up by [portName]
+ /// (defaulting to [defaultPortName]).
+ ///
+ /// This will throw a [StateError] if another [IsolatedAudioHandler] was
+ /// already registered with the given port name. Setting [overridePortName] to
+ /// `true` will unregister any existing port name first. However, this is
+ /// inherently racy and may still throw the same [StateError] if another
+ /// isolate is able to register another new handler with the same name before
+ /// this isolate can.
+ IsolatedAudioHandler(
+ super.inner, {
+ this.portName = defaultPortName,
+ bool overridePortName = false,
+ }) : assert(!kIsWeb) {
+ _receivePort.listen((dynamic event) async {
+ final request = event as _IsolateRequest;
+ switch (request.method) {
+ case 'playbackState':
+ _syncStream(playbackState, request.arguments![0] as SendPort);
+ request.sendPort.send(null);
+ break;
+ case 'queue':
+ _syncStream(queue, request.arguments![0] as SendPort);
+ request.sendPort.send(null);
+ break;
+ case 'queueTitle':
+ _syncStream(queueTitle, request.arguments![0] as SendPort);
+ request.sendPort.send(null);
+ break;
+ case 'mediaItem':
+ _syncStream(mediaItem, request.arguments![0] as SendPort);
+ request.sendPort.send(null);
+ break;
+ case 'androidPlaybackInfo':
+ _syncStream(androidPlaybackInfo, request.arguments![0] as SendPort);
+ request.sendPort.send(null);
+ break;
+ case 'ratingStyle':
+ _syncStream(ratingStyle, request.arguments![0] as SendPort);
+ request.sendPort.send(null);
+ break;
+ case 'customEvent':
+ _syncStream<dynamic>(customEvent, request.arguments![0] as SendPort);
+ request.sendPort.send(null);
+ break;
+ case 'customState':
+ _syncStream<dynamic>(customState, request.arguments![0] as SendPort);
+ request.sendPort.send(null);
+ break;
+ case 'prepare':
+ await prepare();
+ request.sendPort.send(null);
+ break;
+ case 'prepareFromMediaId':
+ await prepareFromMediaId(
+ request.arguments![0] as String,
+ request.arguments![1] as Map<String, dynamic>?,
+ );
+ request.sendPort.send(null);
+ break;
+ case 'prepareFromSearch':
+ await prepareFromSearch(
+ request.arguments![0] as String,
+ request.arguments![1] as Map<String, dynamic>?,
+ );
+ request.sendPort.send(null);
+ break;
+ case 'prepareFromUri':
+ await prepareFromUri(
+ request.arguments![0] as Uri,
+ request.arguments![1] as Map<String, dynamic>?,
+ );
+ request.sendPort.send(null);
+ break;
+ case 'play':
+ await play();
+ request.sendPort.send(null);
+ break;
+ case 'playFromMediaId':
+ await playFromMediaId(
+ request.arguments![0] as String,
+ request.arguments![1] as Map<String, dynamic>?,
+ );
+ request.sendPort.send(null);
+ break;
+ case 'playFromSearch':
+ await playFromSearch(
+ request.arguments![0] as String,
+ request.arguments![1] as Map<String, dynamic>?,
+ );
+ request.sendPort.send(null);
+ break;
+ case 'playFromUri':
+ await playFromUri(
+ request.arguments![0] as Uri,
+ request.arguments![1] as Map<String, dynamic>?,
+ );
+ request.sendPort.send(null);
+ break;
+ case 'playMediaItem':
+ await playMediaItem(request.arguments![0] as MediaItem);
+ request.sendPort.send(null);
+ break;
+ case 'pause':
+ await pause();
+ request.sendPort.send(null);
+ break;
+ case 'click':
+ await click(request.arguments![0] as MediaButton);
+ request.sendPort.send(null);
+ break;
+ case 'stop':
+ await stop();
+ request.sendPort.send(null);
+ break;
+ case 'addQueueItem':
+ await addQueueItem(request.arguments![0] as MediaItem);
+ request.sendPort.send(null);
+ break;
+ case 'addQueueItems':
+ await addQueueItems(request.arguments![0] as List<MediaItem>);
+ request.sendPort.send(null);
+ break;
+ case 'insertQueueItem':
+ await insertQueueItem(
+ request.arguments![0] as int,
+ request.arguments![1] as MediaItem,
+ );
+ request.sendPort.send(null);
+ break;
+ case 'updateQueue':
+ await updateQueue(request.arguments![0] as List<MediaItem>);
+ request.sendPort.send(null);
+ break;
+ case 'updateMediaItem':
+ await updateMediaItem(request.arguments![0] as MediaItem);
+ request.sendPort.send(null);
+ break;
+ case 'removeQueueItem':
+ await removeQueueItem(request.arguments![0] as MediaItem);
+ request.sendPort.send(null);
+ break;
+ case 'removeQueueItemAt':
+ await removeQueueItemAt(request.arguments![0] as int);
+ request.sendPort.send(null);
+ break;
+ case 'skipToNext':
+ await skipToNext();
+ request.sendPort.send(null);
+ break;
+ case 'skipToPrevious':
+ await skipToPrevious();
+ request.sendPort.send(null);
+ break;
+ case 'fastForward':
+ await fastForward();
+ request.sendPort.send(null);
+ break;
+ case 'rewind':
+ await rewind();
+ request.sendPort.send(null);
+ break;
+ case 'skipToQueueItem':
+ await skipToQueueItem(request.arguments![0] as int);
+ request.sendPort.send(null);
+ break;
+ case 'seek':
+ await seek(request.arguments![0] as Duration);
+ request.sendPort.send(null);
+ break;
+ case 'setRating':
+ await setRating(
+ request.arguments![0] as Rating,
+ request.arguments![1] as Map<String, dynamic>?,
+ );
+ request.sendPort.send(null);
+ break;
+ case 'setCaptioningEnabled':
+ await setCaptioningEnabled(request.arguments![0] as bool);
+ request.sendPort.send(null);
+ break;
+ case 'setRepeatMode':
+ await setRepeatMode(request.arguments![0] as AudioServiceRepeatMode);
+ request.sendPort.send(null);
+ break;
+ case 'setShuffleMode':
+ await setShuffleMode(
+ request.arguments![0] as AudioServiceShuffleMode);
+ request.sendPort.send(null);
+ break;
+ case 'seekBackward':
+ await seekBackward(request.arguments![0] as bool);
+ request.sendPort.send(null);
+ break;
+ case 'seekForward':
+ await seekForward(request.arguments![0] as bool);
+ request.sendPort.send(null);
+ break;
+ case 'setSpeed':
+ await setSpeed(request.arguments![0] as double);
+ request.sendPort.send(null);
+ break;
+ case 'customAction':
+ request.sendPort.send(await customAction(
+ request.arguments![0] as String,
+ request.arguments![1] as Map<String, dynamic>?,
+ ));
+ break;
+ case 'onTaskRemoved':
+ await onTaskRemoved();
+ request.sendPort.send(null);
+ break;
+ case 'onNotificationDeleted':
+ await onNotificationDeleted();
+ request.sendPort.send(null);
+ break;
+ case 'getChildren':
+ request.sendPort.send(await getChildren(
+ request.arguments![0] as String,
+ request.arguments![1] as Map<String, dynamic>?,
+ ));
+ break;
+ case 'subscribeToChildren':
+ final parentMediaId = request.arguments![0] as String;
+ final sendPort = request.arguments![1] as SendPort?;
+ subscribeToChildren(parentMediaId).listen(sendPort!.send);
+ break;
+ case 'getMediaItem':
+ final result = await getMediaItem(request.arguments![0] as String);
+ request.sendPort.send(result);
+ break;
+ case 'search':
+ request.sendPort.send(await search(
+ request.arguments![0] as String,
+ request.arguments![1] as Map<String, dynamic>?,
+ ));
+ break;
+ case 'androidAdjustRemoteVolume':
+ await androidAdjustRemoteVolume(
+ request.arguments![0] as AndroidVolumeDirection);
+ request.sendPort.send(null);
+ break;
+ case 'androidSetRemoteVolume':
+ await androidSetRemoteVolume(request.arguments![0] as int);
+ request.sendPort.send(null);
+ break;
+ }
+ });
+ if (overridePortName) {
+ IsolateNameServer.removePortNameMapping(portName);
+ }
+ final success =
+ IsolateNameServer.registerPortWithName(_receivePort.sendPort, portName);
+ if (!success) {
+ throw StateError(
+ 'Port name $portName is already registered by another IsolatedAudioHandler.');
+ }
+ }
+
+ /// Unregisters this handler so that it can no longer be looked up by
+ /// [portName].
+ void unregister() {
+ IsolateNameServer.removePortNameMapping(portName);
+ }
+
+ /// Forwards events from `stream` to the requesting isolate via [sendPort].
+ void _syncStream<T>(Stream<T> stream, SendPort sendPort) {
+ stream.listen(sendPort.send);
+ }
+
+ @override
+ Future<dynamic> customAction(String name,
+ [Map<String, dynamic>? extras]) async {
+ if (name == 'unregister') {
+ unregister();
+ } else {
+ return super.customAction(name, extras);
+ }
+ }
+}
+
+/// A proxy for an [IsolatedAudioHandler] running in another isolate.
+///
+/// All method invocations on this handler will be forwarded to the other
+/// handler, and all stream events emitted by the other handler can be listened
+/// to on this handler.
+class _ClientIsolatedAudioHandler implements BaseAudioHandler {
+ final _childrenSubjects = <String, BehaviorSubject<Map<String, dynamic>>>{};
+
+ /// The port name of the [IsolatedAudioHandler] that this client handler
+ /// connects to.
+ final String portName;
+
+ @override
+ final BehaviorSubject<PlaybackState> playbackState = BehaviorSubject();
+
+ @override
+ final BehaviorSubject<List<MediaItem>> queue = BehaviorSubject();
+
+ @override
+ final BehaviorSubject<String> queueTitle = BehaviorSubject();
+
+ @override
+ final BehaviorSubject<MediaItem?> mediaItem = BehaviorSubject();
+
+ @override
+ final BehaviorSubject<AndroidPlaybackInfo> androidPlaybackInfo =
+ BehaviorSubject();
+
+ @override
+ final BehaviorSubject<RatingStyle> ratingStyle = BehaviorSubject();
+
+ @override
+ final PublishSubject<dynamic> customEvent = PublishSubject<dynamic>();
+
+ @override
+ final BehaviorSubject<dynamic> customState = BehaviorSubject<dynamic>();
+
+ _ClientIsolatedAudioHandler({
+ this.portName = IsolatedAudioHandler.defaultPortName,
+ });
+
+ Future<void> _init() async {
+ await _syncSubject(playbackState, 'playbackState');
+ await _syncSubject(queue, 'queue');
+ await _syncSubject(queueTitle, 'queueTitle');
+ await _syncSubject(mediaItem, 'mediaItem');
+ await _syncSubject(androidPlaybackInfo, 'androidPlaybackInfo');
+ await _syncSubject(ratingStyle, 'ratingStyle');
+ await _syncSubject<dynamic>(customEvent, 'customEvent');
+ await _syncSubject<dynamic>(customState, 'customState');
+ }
+
+ /// Opens a channel to the [IsolatedAudioSource] through which this proxy can
+ /// listen to events on a stream named [name] from that [IsolatedAudioSource]
+ /// and forward them on to this proxy's corresponding stream subject to
+ /// deliver to the client isolate.
+ Future<void> _syncSubject<T>(Subject<T> subject, String name) async {
+ final receivePort = ReceivePort();
+ receivePort.cast<T>().listen(subject.add);
+ await _send(name, <dynamic>[receivePort.sendPort]);
+ }
+
+ @override
+ Future<void> prepare() => _send('prepare');
+
+ @override
+ Future<void> prepareFromMediaId(String mediaId,
+ [Map<String, dynamic>? extras]) =>
+ _send('prepareFromMediaId', <dynamic>[mediaId, extras]);
+
+ @override
+ Future<void> prepareFromSearch(String query,
+ [Map<String, dynamic>? extras]) =>
+ _send('prepareFromSearch', <dynamic>[query, extras]);
+
+ @override
+ Future<void> prepareFromUri(Uri uri, [Map<String, dynamic>? extras]) =>
+ _send('prepareFromUri', <dynamic>[uri, extras]);
+
+ @override
+ Future<void> play() => _send('play');
+
+ @override
+ Future<void> playFromMediaId(String mediaId,
+ [Map<String, dynamic>? extras]) =>
+ _send('playFromMediaId', <dynamic>[mediaId, extras]);
+
+ @override
+ Future<void> playFromSearch(String query, [Map<String, dynamic>? extras]) =>
+ _send('playFromSearch', <dynamic>[query, extras]);
+
+ @override
+ Future<void> playFromUri(Uri uri, [Map<String, dynamic>? extras]) =>
+ _send('playFromUri', <dynamic>[uri, extras]);
+
+ @override
+ Future<void> playMediaItem(MediaItem mediaItem) =>
+ _send('playMediaItem', <dynamic>[mediaItem]);
+
+ @override
+ Future<void> pause() => _send('pause');
+
+ @override
+ Future<void> click([MediaButton button = MediaButton.media]) =>
+ _send('click', <dynamic>[button]);
+
+ @override
+ Future<void> stop() => _send('stop');
+
+ @override
+ Future<void> addQueueItem(MediaItem mediaItem) =>
+ _send('addQueueItem', <dynamic>[mediaItem]);
+
+ @override
+ Future<void> addQueueItems(List<MediaItem> mediaItems) =>
+ _send('addQueueItems', <dynamic>[mediaItems]);
+
+ @override
+ Future<void> insertQueueItem(int index, MediaItem mediaItem) =>
+ _send('insertQueueItem', <dynamic>[index, mediaItem]);
+
+ @override
+ Future<void> updateQueue(List<MediaItem> queue) =>
+ _send('updateQueue', <dynamic>[queue]);
+
+ @override
+ Future<void> updateMediaItem(MediaItem mediaItem) =>
+ _send('updateMediaItem', <dynamic>[mediaItem]);
+
+ @override
+ Future<void> removeQueueItem(MediaItem mediaItem) =>
+ _send('removeQueueItem', <dynamic>[mediaItem]);
+
+ @override
+ Future<void> removeQueueItemAt(int index) =>
+ _send('removeQueueItemAt', <dynamic>[index]);
+
+ @override
+ Future<void> skipToNext() => _send('skipToNext');
+
+ @override
+ Future<void> skipToPrevious() => _send('skipToPrevious');
+
+ @override
+ Future<void> fastForward() => _send('fastForward');
+
+ @override
+ Future<void> rewind() => _send('rewind');
+
+ @override
+ Future<void> skipToQueueItem(int index) =>
+ _send('skipToQueueItem', <dynamic>[index]);
+
+ @override
+ Future<void> seek(Duration position) => _send('seek', <dynamic>[position]);
+
+ @override
+ Future<void> setRating(Rating rating, [Map<String, dynamic>? extras]) =>
+ _send('setRating', <dynamic>[rating, extras]);
+
+ @override
+ Future<void> setCaptioningEnabled(bool enabled) =>
+ _send('setCaptioningEnabled', <dynamic>[enabled]);
+
+ @override
+ Future<void> setRepeatMode(AudioServiceRepeatMode repeatMode) =>
+ _send('setRepeatMode', <dynamic>[repeatMode]);
+
+ @override
+ Future<void> setShuffleMode(AudioServiceShuffleMode shuffleMode) =>
+ _send('setShuffleMode', <dynamic>[shuffleMode]);
+
+ @override
+ Future<void> seekBackward(bool begin) =>
+ _send('seekBackward', <dynamic>[begin]);
+
+ @override
+ Future<void> seekForward(bool begin) =>
+ _send('seekForward', <dynamic>[begin]);
+
+ @override
+ Future<void> setSpeed(double speed) => _send('setSpeed', <dynamic>[speed]);
+
+ @override
+ Future<dynamic> customAction(String name, [Map<String, dynamic>? extras]) =>
+ _send('customAction', <dynamic>[name, extras]);
+
+ @override
+ Future<void> onTaskRemoved() => _send('onTaskRemoved');
+
+ @override
+ Future<void> onNotificationDeleted() => _send('onNotificationDeleted');
+
+ @override
+ Future<List<MediaItem>> getChildren(String parentMediaId,
+ [Map<String, dynamic>? options]) async =>
+ (await _send('getChildren', <dynamic>[parentMediaId, options]))
+ as List<MediaItem>;
+
+ @override
+ ValueStream<Map<String, dynamic>> subscribeToChildren(String parentMediaId) {
+ var childrenSubject = _childrenSubjects[parentMediaId];
+ if (childrenSubject == null) {
+ childrenSubject = _childrenSubjects[parentMediaId] = BehaviorSubject();
+ final receivePort = ReceivePort();
+ receivePort.listen((dynamic options) {
+ childrenSubject!.add(options as Map<String, dynamic>);
+ });
+ _send('subscribeToChildren',
+ <dynamic>[parentMediaId, receivePort.sendPort]);
+ }
+ return childrenSubject;
+ }
+
+ @override
+ Future<MediaItem?> getMediaItem(String mediaId) async =>
+ (await _send('getMediaItem', <dynamic>[mediaId])) as MediaItem?;
+
+ @override
+ Future<List<MediaItem>> search(String query,
+ [Map<String, dynamic>? extras]) async =>
+ (await _send('search', <dynamic>[query, extras])) as List<MediaItem>;
+
+ @override
+ Future<void> androidAdjustRemoteVolume(AndroidVolumeDirection direction) =>
+ _send('androidAdjustRemoteVolume', <dynamic>[direction]);
+
+ @override
+ Future<void> androidSetRemoteVolume(int volumeIndex) =>
+ _send('androidSetRemoteVolume', <dynamic>[volumeIndex]);
+
+ Future<dynamic> _send(String method, [List<dynamic>? arguments]) async {
+ final sendPort = IsolateNameServer.lookupPortByName(portName);
+ if (sendPort == null) {
+ throw StateError('IsolatedAudioHandler $portName not available');
+ }
+ final receivePort = ReceivePort();
+ sendPort.send(_IsolateRequest(receivePort.sendPort, method, arguments));
+ final dynamic result = await receivePort.first;
+ receivePort.close();
+ return result;
+ }
+}
+
+/// Base class for implementations of [AudioHandler]. It provides default
+/// implementations of all methods and streams. Each stream in this class is
+/// specialized as either a [BehaviorSubject] or [PublishSubject] providing an
+/// additional `add` method for emitting values on those streams.
+///
+/// These are [BehaviorSubject]s provided by this class:
+///
+/// * [playbackState]
+/// * [queue]
+/// * [queueTitle]
+/// * [androidPlaybackInfo]
+/// * [ratingStyle]
+///
+/// Besides them, there's also [customEvent] which is a [PublishSubject].
+///
+/// You can choose to implement all methods yourself, or you may leverage some
+/// mixins to provide default implementations of certain behaviours:
+///
+/// * [QueueHandler] provides default implementations of methods for updating
+/// and navigating the queue.
+/// * [SeekHandler] provides default implementations of methods for seeking
+/// forwards and backwards.
+///
+/// ## Android service lifecycle and state transitions
+///
+/// On Android, the [AudioHandler] runs inside an Android service. This allows
+/// the audio logic to continue running in the background, and also an app that
+/// had previously been terminated to wake up and resume playing audio when the
+/// user click on the play button in a media notification or headset.
+///
+/// ### Foreground/background transitions
+///
+/// The underlying Android service enters the `foreground` state whenever
+/// [PlaybackState.playing] becomes `true`, and enters the `background` state
+/// whenever [PlaybackState.playing] becomes `false`.
+///
+/// ### Start/stop transitions
+///
+/// The underlying Android service enters the `started` state whenever
+/// [PlaybackState.playing] becomes `true`, and enters the `stopped` state
+/// whenever [PlaybackState.processingState] becomes `idle`.
+///
+/// ### Create/destroy lifecycle
+///
+/// The underlying service is created either when a client binds to it, or when
+/// it is started, and it is destroyed when no clients are bound to it AND it is
+/// stopped. When the Flutter UI is attached to an Android Activity, this will
+/// also bind to the service, and it will unbind from the service when the
+/// Activity is destroyed. A media notification will also bind to the service.
+///
+/// If the service needs to be created when the app is not already running, your
+/// app's `main` entrypoint will be called in the background which should
+/// initialise your [AudioHandler].
+class BaseAudioHandler extends AudioHandler {
+ /// A controller for broadcasting the current [PlaybackState] to the app's UI,
+ /// media notification and other clients. Example usage:
+ ///
+ /// ```dart
+ /// playbackState.add(playbackState.value!.copyWith(playing: true));
+ /// ```
+ ///
+ /// The state changes broadcast via this stream can be listened to via the
+ /// Flutter app's UI
+ @override
+ final BehaviorSubject<PlaybackState> playbackState =
+ BehaviorSubject.seeded(PlaybackState());
+
+ /// A controller for broadcasting the current queue to the app's UI, media
+ /// notification and other clients. Example usage:
+ ///
+ /// ```dart
+ /// queue.add(queue.value! + [additionalItem]);
+ /// ```
+ @override
+ final BehaviorSubject<List<MediaItem>> queue =
+ BehaviorSubject.seeded(<MediaItem>[]);
+
+ /// A controller for broadcasting the current queue title to the app's UI, media
+ /// notification and other clients. Example usage:
+ ///
+ /// ```dart
+ /// queueTitle.add(newTitle);
+ /// ```
+ @override
+ final BehaviorSubject<String> queueTitle = BehaviorSubject.seeded('');
+
+ /// A controller for broadcasting the current media item to the app's UI,
+ /// media notification and other clients. Example usage:
+ ///
+ /// ```dart
+ /// mediaItem.add(item);
+ /// ```
+ @override
+ final BehaviorSubject<MediaItem?> mediaItem = BehaviorSubject.seeded(null);
+
+ /// A controller for broadcasting the current [AndroidPlaybackInfo] to the app's UI,
+ /// media notification and other clients. Example usage:
+ ///
+ /// ```dart
+ /// androidPlaybackInfo.add(newPlaybackInfo);
+ /// ```
+ @override
+ final BehaviorSubject<AndroidPlaybackInfo> androidPlaybackInfo =
+ BehaviorSubject();
+
+ /// A controller for broadcasting the current rating style to the app's UI,
+ /// media notification and other clients. Example usage:
+ ///
+ /// ```dart
+ /// ratingStyle.add(style);
+ /// ```
+ @override
+ final BehaviorSubject<RatingStyle> ratingStyle = BehaviorSubject();
+
+ /// A controller for broadcasting a custom event to the app's UI.
+ /// A shorthand for the event stream is [customEvent].
+ /// Example usage:
+ ///
+ /// ```dart
+ /// customEventSubject.add(MyCustomEvent(arg: 3));
+ /// ```
+ @override
+ final PublishSubject<dynamic> customEvent = PublishSubject<dynamic>();
+
+ /// A controller for broadcasting the current custom state to the app's UI.
+ /// Example usage:
+ ///
+ /// ```dart
+ /// customState.add(MyCustomState(...));
+ /// ```
+ @override
+ final BehaviorSubject<dynamic> customState = BehaviorSubject<dynamic>();
+
+ /// Constructor. Normally this is called from subclasses via `super`.
+ BaseAudioHandler() : super._();
+
+ @override
+ Future<void> prepare() async {}
+
+ @override
+ Future<void> prepareFromMediaId(String mediaId,
+ [Map<String, dynamic>? extras]) async {}
+
+ @override
+ Future<void> prepareFromSearch(String query,
+ [Map<String, dynamic>? extras]) async {}
+
+ @override
+ Future<void> prepareFromUri(Uri uri, [Map<String, dynamic>? extras]) async {}
+
+ @override
+ Future<void> play() async {}
+
+ @override
+ Future<void> playFromMediaId(String mediaId,
+ [Map<String, dynamic>? extras]) async {}
+
+ @override
+ Future<void> playFromSearch(String query,
+ [Map<String, dynamic>? extras]) async {}
+
+ @override
+ Future<void> playFromUri(Uri uri, [Map<String, dynamic>? extras]) async {}
+
+ @override
+ Future<void> playMediaItem(MediaItem mediaItem) async {}
+
+ @override
+ Future<void> pause() async {}
+
+ @override
+ Future<void> click([MediaButton button = MediaButton.media]) async {
+ switch (button) {
+ case MediaButton.media:
+ if (playbackState.nvalue?.playing == true) {
+ await pause();
+ } else {
+ await play();
+ }
+ break;
+ case MediaButton.next:
+ await skipToNext();
+ break;
+ case MediaButton.previous:
+ await skipToPrevious();
+ break;
+ }
+ }
+
+ /// Stop playback and release resources.
+ ///
+ /// The default implementation (which may be overridden) updates
+ /// [playbackState] by setting the processing state to
+ /// [AudioProcessingState.idle] which disables the system notification.
+ @override
+ Future<void> stop() async {
+ playbackState.add(playbackState.nvalue!
+ .copyWith(processingState: AudioProcessingState.idle));
+ await playbackState.firstWhere(
+ (state) => state.processingState == AudioProcessingState.idle);
+ }
+
+ @override
+ Future<void> addQueueItem(MediaItem mediaItem) async {}
+
+ @override
+ Future<void> addQueueItems(List<MediaItem> mediaItems) async {}
+
+ @override
+ Future<void> insertQueueItem(int index, MediaItem mediaItem) async {}
+
+ @override
+ Future<void> updateQueue(List<MediaItem> queue) async {}
+
+ @override
+ Future<void> updateMediaItem(MediaItem mediaItem) async {}
+
+ @override
+ Future<void> removeQueueItem(MediaItem mediaItem) async {}
+
+ @override
+ Future<void> removeQueueItemAt(int index) async {}
+
+ @override
+ Future<void> skipToNext() async {}
+
+ @override
+ Future<void> skipToPrevious() async {}
+
+ @override
+ Future<void> fastForward() async {}
+
+ @override
+ Future<void> rewind() async {}
+
+ @override
+ Future<void> skipToQueueItem(int index) async {}
+
+ @override
+ Future<void> seek(Duration position) async {}
+
+ @override
+ Future<void> setRating(Rating rating, [Map<String, dynamic>? extras]) async {}
+
+ @override
+ Future<void> setCaptioningEnabled(bool enabled) async {}
+
+ @override
+ Future<void> setRepeatMode(AudioServiceRepeatMode repeatMode) async {}
+
+ @override
+ Future<void> setShuffleMode(AudioServiceShuffleMode shuffleMode) async {}
+
+ @override
+ Future<void> seekBackward(bool begin) async {}
+
+ @override
+ Future<void> seekForward(bool begin) async {}
+
+ @override
+ Future<void> setSpeed(double speed) async {}
+
+ @override
+ Future<dynamic> customAction(String name,
+ [Map<String, dynamic>? extras]) async {}
+
+ @override
+ Future<void> onTaskRemoved() async {}
+
+ @override
+ Future<void> onNotificationDeleted() async {
+ await stop();
+ }
+
+ @override
+ Future<List<MediaItem>> getChildren(String parentMediaId,
+ [Map<String, dynamic>? options]) async =>
+ [];
+
+ @override
+ ValueStream<Map<String, dynamic>> subscribeToChildren(String parentMediaId) =>
+ BehaviorSubject.seeded(<String, dynamic>{});
+
+ @override
+ Future<MediaItem?> getMediaItem(String mediaId) async => null;
+
+ @override
+ Future<List<MediaItem>> search(String query,
+ [Map<String, dynamic>? extras]) async =>
+ [];
+
+ @override
+ Future<void> androidAdjustRemoteVolume(
+ AndroidVolumeDirection direction) async {}
+
+ @override
+ Future<void> androidSetRemoteVolume(int volumeIndex) async {}
+}
+
+/// This mixin provides default implementations of [fastForward], [rewind],
+/// [seekForward] and [seekBackward] which are all defined in terms of your own
+/// implementation of [seek].
+mixin SeekHandler on BaseAudioHandler {
+ _Seeker? _seeker;
+
+ @override
+ Future<void> fastForward() =>
+ _seekRelative(AudioService.config.fastForwardInterval);
+
+ @override
+ Future<void> rewind() => _seekRelative(-AudioService.config.rewindInterval);
+
+ @override
+ Future<void> seekForward(bool begin) async => _seekContinuously(begin, 1);
+
+ @override
+ Future<void> seekBackward(bool begin) async => _seekContinuously(begin, -1);
+
+ /// Jumps away from the current position by [offset].
+ Future<void> _seekRelative(Duration offset) async {
+ var newPosition = playbackState.nvalue!.position + offset;
+ // Make sure we don't jump out of bounds.
+ if (newPosition < Duration.zero) {
+ newPosition = Duration.zero;
+ }
+ final duration = mediaItem.nvalue?.duration ?? Duration.zero;
+ if (newPosition > duration) {
+ newPosition = duration;
+ }
+ // Perform the jump via a seek.
+ await seek(newPosition);
+ }
+
+ /// Begins or stops a continuous seek in [direction]. After it begins it will
+ /// continue seeking forward or backward by 10 seconds within the audio, at
+ /// intervals of 1 second in app time.
+ void _seekContinuously(bool begin, int direction) {
+ _seeker?.stop();
+ if (begin && mediaItem.nvalue?.duration != null) {
+ _seeker = _Seeker(this, Duration(seconds: 10 * direction),
+ const Duration(seconds: 1), mediaItem.nvalue!.duration!)
+ ..start();
+ }
+ }
+}
+
+class _Seeker {
+ final AudioHandler handler;
+ final Duration positionInterval;
+ final Duration stepInterval;
+ final Duration duration;
+ bool _running = false;
+
+ _Seeker(
+ this.handler,
+ this.positionInterval,
+ this.stepInterval,
+ this.duration,
+ );
+
+ Future<void> start() async {
+ _running = true;
+ while (_running) {
+ var newPosition =
+ handler.playbackState.nvalue!.position + positionInterval;
+ if (newPosition < Duration.zero) newPosition = Duration.zero;
+ if (newPosition > duration) newPosition = duration;
+ handler.seek(newPosition);
+ await Future<void>.delayed(stepInterval);
+ }
+ }
+
+ void stop() {
+ _running = false;
+ }
+}
+
+/// This mixin provides default implementations of methods for updating and
+/// navigating the queue. When using this mixin, you must add a list of
+/// [MediaItem]s to [queue], override [skipToQueueItem] and initialise the queue
+/// index (e.g. by calling [skipToQueueItem] with the initial queue index). The
+/// [skipToNext] and [skipToPrevious] default implementations are defined by
+/// this mixin in terms of your own implementation of [skipToQueueItem].
+mixin QueueHandler on BaseAudioHandler {
+ @override
+ Future<void> addQueueItem(MediaItem mediaItem) async {
+ queue.add(queue.nvalue!..add(mediaItem));
+ await super.addQueueItem(mediaItem);
+ }
+
+ @override
+ Future<void> addQueueItems(List<MediaItem> mediaItems) async {
+ queue.add(queue.nvalue!..addAll(mediaItems));
+ await super.addQueueItems(mediaItems);
+ }
+
+ @override
+ Future<void> insertQueueItem(int index, MediaItem mediaItem) async {
+ queue.add(queue.nvalue!..insert(index, mediaItem));
+ await super.insertQueueItem(index, mediaItem);
+ }
+
+ @override
+ Future<void> updateQueue(List<MediaItem> queue) async {
+ this.queue.add(
+ this.queue.nvalue!..replaceRange(0, this.queue.nvalue!.length, queue));
+ await super.updateQueue(queue);
+ }
+
+ @override
+ Future<void> updateMediaItem(MediaItem mediaItem) async {
+ queue.add(queue.nvalue!..[queue.nvalue!.indexOf(mediaItem)] = mediaItem);
+ await super.updateMediaItem(mediaItem);
+ }
+
+ @override
+ Future<void> removeQueueItem(MediaItem mediaItem) async {
+ queue.add(queue.nvalue!..remove(mediaItem));
+ await super.removeQueueItem(mediaItem);
+ }
+
+ @override
+ Future<void> skipToNext() async {
+ await _skip(1);
+ await super.skipToNext();
+ }
+
+ @override
+ Future<void> skipToPrevious() async {
+ await _skip(-1);
+ await super.skipToPrevious();
+ }
+
+ /// This should be overridden to skip to the queue item at [index].
+ /// Implementations should broadcast the new queue index via [playbackState],
+ /// broadcast the new media item via [mediaItem], and potentially issue
+ /// instructions to start the new item playing. Some implementations may
+ /// choose to automatically play when skipping to a queue item while others
+ /// may prefer to play the new item only if the player was already playing
+ /// another item beforehand.
+ ///
+ /// An example implementation may look like:
+ ///
+ /// ```dart
+ /// playbackState.add(playbackState.value!.copyWith(queueIndex: index));
+ /// mediaItem.add(queue.value![index]);
+ /// player.playAtIndex(index); // use your player's respective API
+ /// await super.skipToQueueItem(index);
+ /// ```
+ @override
+ Future<void> skipToQueueItem(int index) async {
+ await super.skipToQueueItem(index);
+ }
+
+ Future<void> _skip(int offset) async {
+ final queue = this.queue.nvalue!;
+ final index = playbackState.nvalue!.queueIndex!;
+ if (index < 0 || index >= queue.length) return;
+ return skipToQueueItem(index + offset);
+ }
+}
+
+/// The available shuffle modes for the queue.
+enum AudioServiceShuffleMode {
+ /// The queue will not be shuffled.
+ none,
+
+ /// The whole queue will be shuffled.
+ all,
+
+ /// A group of items will be shuffled. This corresponds to Android's
+ /// [SHUFFLE_MODE_GROUP](https://developer.android.com/reference/androidx/media2/common/SessionPlayer#SHUFFLE_MODE_GROUP).
+ group,
+}
+
+/// The available repeat modes.
+///
+/// This defines how media items should repeat when the current one is finished.
+enum AudioServiceRepeatMode {
+ /// The current media item or queue will not repeat.
+ none,
+
+ /// The current media item will repeat.
+ one,
+
+ /// Playback will continue looping through all media items in the current list.
+ all,
+
+ /// UNIMPLEMENTED - see https://github.com/ryanheise/audio_service/issues/560
+ ///
+ /// This corresponds to Android's [REPEAT_MODE_GROUP](https://developer.android.com/reference/androidx/media2/common/SessionPlayer#REPEAT_MODE_GROUP).
+ ///
+ /// This could represent a playlist that is a smaller subset of all media items.
+ group,
+}
+
+/// The configuration options to use when intializing the [AudioService].
+class AudioServiceConfig {
+ /// Whether on Android a media button click wakes up the media session and
+ /// resumes playback.
+ // TODO: either fix, or remove this https://github.com/ryanheise/audio_service/issues/638
+ final bool androidResumeOnClick;
+
+ /// The ID of the media notification channel. This will default to
+ /// `<YOUR_PACKAGE_NAME>.channel` where `<YOUR_PACKAGE_NAME>` is your app's
+ /// package name. e.g. `com.mycompany.myapp.channel`.
+ ///
+ /// If your app uses multiple notification channels, make sure each channel
+ /// has a unique ID so that they don't clash. It is recommended to override
+ /// the default ID.
+ ///
+ /// NOTE: After a user installs and runs your app, a channel will be created
+ /// with this ID and will show up in the app's settings. If you subsequently
+ /// change this channel ID here, it will result in a new channel being created
+ /// under the new ID leaving the old channel still visible. Therefore, if your
+ /// app has already been published, you might prefer to keep using the same
+ /// channel ID that you are currently using.
+ final String? androidNotificationChannelId;
+
+ /// The name of the media notification channel, that is visible to user in
+ /// settings of your app.
+ final String androidNotificationChannelName;
+
+ /// A description of the media notification channel, that is visible to user
+ /// in settings of your app.
+ final String? androidNotificationChannelDescription;
+
+ /// The color to use on the background of the notification on Android. This
+ /// should be a non-transparent color.
+ final Color? notificationColor;
+
+ /// The icon resource to be used in the Android media notification, specified
+ /// like an XML resource reference. This should be a monochrome white icon on
+ /// a transparent background. The default value is `"mipmap/ic_launcher"`.
+ final String androidNotificationIcon;
+
+ /// Whether notification badges (also known as notification dots) should
+ /// appear on a launcher icon when the app has an active notification.
+ final bool androidShowNotificationBadge;
+
+ /// Whether the application activity will be opened on click on notification.
+ final bool androidNotificationClickStartsActivity;
+
+ /// Whether the notification can be swiped away.
+ ///
+ /// If you set this to true, [androidStopForegroundOnPause] must be true as well,
+ /// otherwise this will not do anything, because when foreground service is active,
+ /// it forces notification to be ongoing.
+ final bool androidNotificationOngoing;
+
+ /// Whether the Android service should switch to a lower priority state when
+ /// playback is paused allowing the user to swipe away the notification. Note
+ /// that while in this lower priority state, the operating system will also be
+ /// able to kill your service at any time to reclaim resources.
+ final bool androidStopForegroundOnPause;
+
+ /// If not null, causes the artwork specified by [MediaItem.artUri] to be
+ /// downscaled to this maximum pixel width. If the resolution of your artwork
+ /// is particularly high, this can help to conserve memory. If specified,
+ /// [artDownscaleHeight] must also be specified.
+ final int? artDownscaleWidth;
+
+ /// If not null, causes the artwork specified by [MediaItem.artUri] to be
+ /// downscaled to this maximum pixel height. If the resolution of your artwork
+ /// is particularly high, this can help to conserve memory. If specified,
+ /// [artDownscaleWidth] must also be specified.
+ final int? artDownscaleHeight;
+
+ /// The interval to be used in [AudioHandler.fastForward]. This value will
+ /// also be used on iOS to render the skip-forward button. This value must be
+ /// positive.
+ final Duration fastForwardInterval;
+
+ /// The interval to be used in [AudioHandler.rewind]. This value will also be
+ /// used on iOS to render the skip-backward button. This value must be
+ /// positive.
+ final Duration rewindInterval;
+
+ /// By default artworks are loaded only when the item is fed into [AudioHandler.mediaItem].
+ ///
+ /// If set to `true`, artworks for items start loading as soon as they are added to
+ /// [AudioHandler.queue].
+ final bool preloadArtwork;
+
+ /// Extras to report on Android in response to an `onGetRoot` request.
+ final Map<String, dynamic>? androidBrowsableRootExtras;
+
+ /// Creates a configuration object.
+ const AudioServiceConfig({
+ this.androidResumeOnClick = true,
+ this.androidNotificationChannelId,
+ this.androidNotificationChannelName = 'Notifications',
+ this.androidNotificationChannelDescription,
+ this.notificationColor,
+ this.androidNotificationIcon = 'mipmap/ic_launcher',
+ this.androidShowNotificationBadge = false,
+ this.androidNotificationClickStartsActivity = true,
+ this.androidNotificationOngoing = false,
+ this.androidStopForegroundOnPause = true,
+ this.artDownscaleWidth,
+ this.artDownscaleHeight,
+ this.fastForwardInterval = const Duration(seconds: 10),
+ this.rewindInterval = const Duration(seconds: 10),
+ this.preloadArtwork = false,
+ this.androidBrowsableRootExtras,
+ }) : assert((artDownscaleWidth != null) == (artDownscaleHeight != null)),
+ assert(
+ !androidNotificationOngoing || androidStopForegroundOnPause,
+ 'The androidNotificationOngoing will make no effect with androidStopForegroundOnPause set to false',
+ );
+
+ AudioServiceConfigMessage _toMessage() => AudioServiceConfigMessage(
+ androidResumeOnClick: androidResumeOnClick,
+ androidNotificationChannelId: androidNotificationChannelId,
+ androidNotificationChannelName: androidNotificationChannelName,
+ androidNotificationChannelDescription:
+ androidNotificationChannelDescription,
+ notificationColor: notificationColor,
+ androidNotificationIcon: androidNotificationIcon,
+ androidShowNotificationBadge: androidShowNotificationBadge,
+ androidNotificationClickStartsActivity:
+ androidNotificationClickStartsActivity,
+ androidNotificationOngoing: androidNotificationOngoing,
+ androidStopForegroundOnPause: androidStopForegroundOnPause,
+ artDownscaleWidth: artDownscaleWidth,
+ artDownscaleHeight: artDownscaleHeight,
+ fastForwardInterval: fastForwardInterval,
+ rewindInterval: rewindInterval,
+ preloadArtwork: preloadArtwork,
+ androidBrowsableRootExtras: androidBrowsableRootExtras,
+ );
+
+ @override
+ String toString() => '${_toMessage().toMap()}';
+}
+
+/// Key/value codes for use in [MediaItem.extras] and
+/// [AudioServiceConfig.androidBrowsableRootExtras] to influence how Android
+/// Auto will style browsable and playable media items.
+class AndroidContentStyle {
+ /// Set this key to `true` in [AudioServiceConfig.androidBrowsableRootExtras]
+ /// to declare that content style is supported.
+ static const supportedKey = 'android.media.browse.CONTENT_STYLE_SUPPORTED';
+
+ /// The key in [MediaItem.extras] and
+ /// [AudioServiceConfig.androidBrowsableRootExtras] to configure the content
+ /// style for playable items. The value can be any of the `*ItemHintValue`
+ /// constants defined in this class.
+ static const playableHintKey =
+ 'android.media.browse.CONTENT_STYLE_PLAYABLE_HINT';
+
+ /// The key in [MediaItem.extras] and
+ /// [AudioServiceConfig.androidBrowsableRootExtras] to configure the content
+ /// style for browsable items. The value can be any of the `*ItemHintValue`
+ /// constants defined in this class.
+ static const browsableHintKey =
+ 'android.media.browse.CONTENT_STYLE_BROWSABLE_HINT';
+
+ /// Specifies that items should be presented as lists.
+ static const listItemHintValue = 1;
+
+ /// Specifies that items should be presented as grids.
+ static const gridItemHintValue = 2;
+
+ /// Specifies that items should be presented as lists with vector icons.
+ static const categoryListItemHintValue = 3;
+
+ /// Specifies that items should be presented as grids with vector icons.
+ static const categoryGridItemHintValue = 4;
+}
+
+/// (Maybe) temporary.
+extension AudioServiceValueStream<T> on ValueStream<T> {
+ /// Returns `this`.
+ @Deprecated('Use "this" instead. Will be removed before the release')
+ ValueStream<T> get stream => this;
+}
+
+extension _MediaItemMessageExtension on MediaItemMessage {
+ MediaItem toPlugin() => MediaItem(
+ id: id,
+ album: album,
+ title: title,
+ artist: artist,
+ genre: genre,
+ duration: duration,
+ artUri: artUri,
+ playable: playable,
+ displayTitle: displayTitle,
+ displaySubtitle: displaySubtitle,
+ displayDescription: displayDescription,
+ rating: rating?.toPlugin(),
+ isLive: isLive,
+ extras: extras,
+ );
+}
+
+extension _RatingMessageExtension on RatingMessage {
+ Rating toPlugin() => Rating._(RatingStyle.values[type.index], value);
+}
+
+extension _AndroidVolumeDirectionMessageExtension
+ on AndroidVolumeDirectionMessage {
+ AndroidVolumeDirection toPlugin() => AndroidVolumeDirection.values[index]!;
+}
+
+extension _MediaButtonMessageExtension on MediaButtonMessage {
+ MediaButton toPlugin() => MediaButton.values[index];
+}
+
+/// An enum of volume direction controls on Android.
+class AndroidVolumeDirection {
+ /// Lower the ringer volume.
+ static final lower = AndroidVolumeDirection._(-1);
+
+ /// Keep the previous ringer volume.
+ static final same = AndroidVolumeDirection._(0);
+
+ /// Raise the ringer volume.
+ static final raise = AndroidVolumeDirection._(1);
+
+ /// A map of indices to values.
+ static final values = <int, AndroidVolumeDirection>{
+ -1: lower,
+ 0: same,
+ 1: raise,
+ };
+
+ /// The index for this enum value.
+ final int index;
+
+ AndroidVolumeDirection._(this.index);
+
+ @override
+ String toString() => '$index';
+}
+
+/// An enumeration of different volume control types on Android.
+enum AndroidVolumeControlType {
+ /// The volume cannot be changed.
+ fixed,
+
+ /// The volume can be adjusted relatively.
+ relative,
+
+ /// The volume can be set using an absolute value.
+ absolute,
+}
+
+/// Information about volume control for either local or remote playback
+/// depending on the subclass.
+abstract class AndroidPlaybackInfo {
+ AndroidPlaybackInfoMessage _toMessage();
+
+ @override
+ String toString() => '${_toMessage().toMap()}';
+}
+
+/// Playback information for remote volume handling.
+class RemoteAndroidPlaybackInfo extends AndroidPlaybackInfo {
+ //final AndroidAudioAttributes audioAttributes;
+
+ /// The type of volume control supported by the session.
+ final AndroidVolumeControlType volumeControlType;
+
+ /// The maximum volume supported.
+ final int maxVolume;
+
+ /// The current volume.
+ final int volume;
+
+ // ignore: public_member_api_docs
+ RemoteAndroidPlaybackInfo({
+ required this.volumeControlType,
+ required this.maxVolume,
+ required this.volume,
+ });
+
+ /// Creates a copy of this object with fields replaced.
+ AndroidPlaybackInfo copyWith({
+ AndroidVolumeControlType? volumeControlType,
+ int? maxVolume,
+ int? volume,
+ }) =>
+ RemoteAndroidPlaybackInfo(
+ volumeControlType: volumeControlType ?? this.volumeControlType,
+ maxVolume: maxVolume ?? this.maxVolume,
+ volume: volume ?? this.volume,
+ );
+
+ @override
+ bool operator ==(Object other) =>
+ other.runtimeType == runtimeType &&
+ other is RemoteAndroidPlaybackInfo &&
+ volumeControlType == other.volumeControlType &&
+ maxVolume == other.maxVolume &&
+ volume == other.volume;
+
+ @override
+ int get hashCode => Object.hash(volumeControlType, maxVolume, volume);
+
+ @override
+ RemoteAndroidPlaybackInfoMessage _toMessage() =>
+ RemoteAndroidPlaybackInfoMessage(
+ volumeControlType:
+ AndroidVolumeControlTypeMessage.values[volumeControlType.index],
+ maxVolume: maxVolume,
+ volume: volume,
+ );
+}
+
+/// Playback information for local volume handling.
+class LocalAndroidPlaybackInfo extends AndroidPlaybackInfo {
+ @override
+ bool operator ==(Object other) => other.runtimeType == runtimeType;
+
+ @override
+ int get hashCode => 0;
+
+ @override
+ LocalAndroidPlaybackInfoMessage _toMessage() =>
+ const LocalAndroidPlaybackInfoMessage();
+}
+
+/// This class is deprecated. Use the stream subjects in [BaseAudioHandler]
+/// instead.
+@Deprecated("Use stream subjects in BaseAudioHandler instead.")
+class AudioServiceBackground {
+ static SwitchAudioHandler get _handler =>
+ AudioService._handler as SwitchAudioHandler;
+ static Completer<BackgroundAudioTask>? _startCompleter;
+
+ /// Deprecated. Use [AudioHandler.playbackState] instead.
+ @Deprecated("Use AudioHandler.playbackState instead.")
+ static PlaybackState get state =>
+ _handler.playbackState.nvalue ?? PlaybackState();
+
+ /// Deprecated. Use [AudioHandler.queue] instead.
+ @Deprecated("Use AudioHandler.queue instead.")
+ static List<MediaItem>? get queue => _handler.queue.nvalue;
+
+ /// Deprecated. Use [AudioService.init] instead.
+ @Deprecated("Use AudioService.init instead")
+ static Future<void> run(BackgroundAudioTask Function() taskBuilder) async {
+ final task = taskBuilder();
+ _startCompleter!.complete(task);
+ }
+
+ /// Deprecated. Use [BaseAudioHandler.playbackState] instead.
+ @Deprecated("Use BaseAudioHandler.playbackState instead.")
+ static Future<void> setState({
+ List<MediaControl>? controls,
+ List<MediaAction>? systemActions,
+ AudioProcessingState? processingState,
+ bool? playing,
+ Duration? position,
+ Duration? bufferedPosition,
+ double? speed,
+ DateTime? updateTime,
+ List<int>? androidCompactActions,
+ AudioServiceRepeatMode? repeatMode,
+ AudioServiceShuffleMode? shuffleMode,
+ }) async {
+ final oldState = _handler.playbackState.nvalue!;
+ _taskHandler.playbackState.add(PlaybackState(
+ controls: controls ?? oldState.controls,
+ systemActions: systemActions?.toSet() ?? oldState.systemActions,
+ processingState: processingState ?? oldState.processingState,
+ playing: playing ?? oldState.playing,
+ updatePosition: position ?? oldState.position,
+ bufferedPosition: bufferedPosition ?? oldState.bufferedPosition,
+ speed: speed ?? oldState.speed,
+ androidCompactActionIndices:
+ androidCompactActions ?? oldState.androidCompactActionIndices,
+ repeatMode: repeatMode ?? oldState.repeatMode,
+ shuffleMode: shuffleMode ?? oldState.shuffleMode,
+ ));
+ }
+
+ static _BackgroundAudioHandler get _taskHandler =>
+ _handler.inner as _BackgroundAudioHandler;
+
+ /// Deprecated. Use [BaseAudioHandler.queue] instead.
+ @Deprecated("Use BaseAudioHandler.queue instead.")
+ static Future<void> setQueue(List<MediaItem> queue,
+ {bool preloadArtwork = false}) async {
+ if (preloadArtwork) {
+ // ignore: avoid_print
+ print(
+ 'WARNING: preloadArtwork is not enabled! '
+ 'This is deprecated and must be set via AudioService.init()',
+ );
+ }
+ _taskHandler.queue.add(queue);
+ }
+
+ /// Deprecated. Use [BaseAudioHandler.mediaItem] instead.
+ @Deprecated("Use BaseAudioHandler.mediaItem instead.")
+ static Future<void> setMediaItem(MediaItem mediaItem) async {
+ _taskHandler.mediaItem.add(mediaItem);
+ }
+
+ /// Deprecated. Use [AudioHandler.subscribeToChildren] instead.
+ @Deprecated("Use AudioHandler.subscribeToChildren instead.")
+ static Future<void> notifyChildrenChanged(
+ [String parentMediaId = AudioService.browsableRootId]) async {
+ await _platform.notifyChildrenChanged(
+ NotifyChildrenChangedRequest(parentMediaId: parentMediaId));
+ }
+
+ /// Deprecated. Use [AudioService.androidForceEnableMediaButtons] instead.
+ @Deprecated("Use AudioService.androidForceEnableMediaButtons instead.")
+ static Future<void> androidForceEnableMediaButtons() async {
+ await AudioService.androidForceEnableMediaButtons();
+ }
+
+ /// Deprecated. Use [BaseAudioHandler.customEvent] instead.
+ @Deprecated("Use BaseAudioHandler.customEvent instead.")
+ static void sendCustomEvent(dynamic event) {
+ _taskHandler.customEvent.add(event);
+ }
+}
+
+class _HandlerCallbacks extends AudioHandlerCallbacks {
+ final _handlerCompleter = Completer<AudioHandler>();
+
+ Future<AudioHandler> get handlerFuture => _handlerCompleter.future;
+
+ void setHandler(AudioHandler handler) => _handlerCompleter.complete(handler);
+
+ @override
+ Future<void> addQueueItem(AddQueueItemRequest request) async =>
+ (await handlerFuture).addQueueItem(request.mediaItem.toPlugin());
+
+ @override
+ Future<void> androidAdjustRemoteVolume(
+ AndroidAdjustRemoteVolumeRequest request) async =>
+ (await handlerFuture)
+ .androidAdjustRemoteVolume(request.direction.toPlugin());
+
+ @override
+ Future<void> androidSetRemoteVolume(
+ AndroidSetRemoteVolumeRequest request) async =>
+ (await handlerFuture).androidSetRemoteVolume(request.volumeIndex);
+
+ @override
+ Future<void> click(ClickRequest request) async {
+ return (await handlerFuture).click(request.button.toPlugin());
+ }
+
+ @override
+ Future<dynamic> customAction(CustomActionRequest request) async =>
+ (await handlerFuture).customAction(request.name, request.extras);
+
+ @override
+ Future<void> fastForward(FastForwardRequest request) async =>
+ (await handlerFuture).fastForward();
+
+ @override
+ Future<GetChildrenResponse> getChildren(GetChildrenRequest request) async {
+ final mediaItems =
+ await _onLoadChildren(request.parentMediaId, request.options);
+ return GetChildrenResponse(
+ children: mediaItems.map((item) => item._toMessage()).toList());
+ }
+
+ @override
+ Future<GetMediaItemResponse> getMediaItem(GetMediaItemRequest request) async {
+ return GetMediaItemResponse(
+ mediaItem: (await (await handlerFuture).getMediaItem(request.mediaId))
+ ?._toMessage());
+ }
+
+ @override
+ Future<void> insertQueueItem(InsertQueueItemRequest request) async =>
+ (await handlerFuture)
+ .insertQueueItem(request.index, request.mediaItem.toPlugin());
+
+ @override
+ Future<void> onNotificationClicked(
+ OnNotificationClickedRequest request) async {
+ AudioService._notificationClicked.add(request.clicked);
+ }
+
+ @override
+ Future<void> onNotificationDeleted(
+ OnNotificationDeletedRequest request) async =>
+ (await handlerFuture).onNotificationDeleted();
+
+ @override
+ Future<void> onTaskRemoved(OnTaskRemovedRequest request) async =>
+ (await handlerFuture).onTaskRemoved();
+
+ @override
+ Future<void> pause(PauseRequest request) async =>
+ (await handlerFuture).pause();
+
+ @override
+ Future<void> play(PlayRequest request) async => (await handlerFuture).play();
+
+ @override
+ Future<void> playFromMediaId(PlayFromMediaIdRequest request) async =>
+ (await handlerFuture).playFromMediaId(request.mediaId, request.extras);
+
+ @override
+ Future<void> playFromSearch(PlayFromSearchRequest request) async =>
+ (await handlerFuture).playFromSearch(request.query, request.extras);
+
+ @override
+ Future<void> playFromUri(PlayFromUriRequest request) async =>
+ (await handlerFuture).playFromUri(request.uri, request.extras);
+
+ @override
+ Future<void> playMediaItem(PlayMediaItemRequest request) async =>
+ (await handlerFuture).playMediaItem(request.mediaItem.toPlugin());
+
+ @override
+ Future<void> prepare(PrepareRequest request) async =>
+ (await handlerFuture).prepare();
+
+ @override
+ Future<void> prepareFromMediaId(PrepareFromMediaIdRequest request) async =>
+ (await handlerFuture).prepareFromMediaId(request.mediaId, request.extras);
+
+ @override
+ Future<void> prepareFromSearch(PrepareFromSearchRequest request) async =>
+ (await handlerFuture).prepareFromSearch(request.query, request.extras);
+
+ @override
+ Future<void> prepareFromUri(PrepareFromUriRequest request) async =>
+ (await handlerFuture).prepareFromUri(request.uri, request.extras);
+
+ @override
+ Future<void> removeQueueItem(RemoveQueueItemRequest request) async =>
+ (await handlerFuture).removeQueueItem(request.mediaItem.toPlugin());
+
+ @override
+ Future<void> removeQueueItemAt(RemoveQueueItemAtRequest request) async =>
+ (await handlerFuture).removeQueueItemAt(request.index);
+
+ @override
+ Future<void> rewind(RewindRequest request) async =>
+ (await handlerFuture).rewind();
+
+ @override
+ Future<SearchResponse> search(SearchRequest request) async => SearchResponse(
+ mediaItems:
+ (await (await handlerFuture).search(request.query, request.extras))
+ .map((item) => item._toMessage())
+ .toList());
+
+ @override
+ Future<void> seek(SeekRequest request) async =>
+ (await handlerFuture).seek(request.position);
+
+ @override
+ Future<void> seekBackward(SeekBackwardRequest request) async =>
+ (await handlerFuture).seekBackward(request.begin);
+
+ @override
+ Future<void> seekForward(SeekForwardRequest request) async =>
+ (await handlerFuture).seekForward(request.begin);
+
+ @override
+ Future<void> setCaptioningEnabled(
+ SetCaptioningEnabledRequest request) async =>
+ (await handlerFuture).setCaptioningEnabled(request.enabled);
+
+ @override
+ Future<void> setRating(SetRatingRequest request) async =>
+ (await handlerFuture)
+ .setRating(request.rating.toPlugin(), request.extras);
+
+ @override
+ Future<void> setRepeatMode(SetRepeatModeRequest request) async =>
+ (await handlerFuture).setRepeatMode(
+ AudioServiceRepeatMode.values[request.repeatMode.index]);
+
+ @override
+ Future<void> setShuffleMode(SetShuffleModeRequest request) async =>
+ (await handlerFuture).setShuffleMode(
+ AudioServiceShuffleMode.values[request.shuffleMode.index]);
+
+ @override
+ Future<void> setSpeed(SetSpeedRequest request) async =>
+ (await handlerFuture).setSpeed(request.speed);
+
+ @override
+ Future<void> skipToNext(SkipToNextRequest request) async =>
+ (await handlerFuture).skipToNext();
+
+ @override
+ Future<void> skipToPrevious(SkipToPreviousRequest request) async =>
+ (await handlerFuture).skipToPrevious();
+
+ @override
+ Future<void> skipToQueueItem(SkipToQueueItemRequest request) async =>
+ (await handlerFuture).skipToQueueItem(request.index);
+
+ @override
+ Future<void> stop(StopRequest request) async => (await handlerFuture).stop();
+
+ final Map<String, ValueStream<Map<String, dynamic>>> _childrenSubscriptions =
+ {};
+
+ Future<List<MediaItem>> _onLoadChildren(
+ String parentMediaId, Map<String, dynamic>? options) async {
+ var childrenSubscription = _childrenSubscriptions[parentMediaId];
+ if (childrenSubscription == null) {
+ childrenSubscription = _childrenSubscriptions[parentMediaId] =
+ (await handlerFuture).subscribeToChildren(parentMediaId);
+ childrenSubscription.listen((Map<String, dynamic>? options) {
+ // Notify clients that the children of [parentMediaId] have changed.
+ _platform.notifyChildrenChanged(NotifyChildrenChangedRequest(
+ parentMediaId: parentMediaId,
+ options: options,
+ ));
+ });
+ }
+ return await (await handlerFuture).getChildren(parentMediaId, options);
+ }
+}
+
+/// Backwards compatible extensions on rxdart's ValueStream
+extension _ValueStreamExtension<T> on ValueStream<T> {
+ /// Backwards compatible version of valueOrNull.
+ T? get nvalue => hasValue ? value : null;
+}
+
+/// This widget is no longer required and has been deprecated.
+@Deprecated("This widget is no longer required and can be safely removed.")
+class AudioServiceWidget extends StatelessWidget {
+ /// Deprecated.
+ final Widget child;
+
+ /// Deprecated.
+ const AudioServiceWidget({super.key, required this.child});
+
+ @override
+ Widget build(BuildContext context) {
+ return child;
+ }
+}
diff --git a/packages/audio_service/pubspec.yaml b/packages/audio_service/pubspec.yaml
new file mode 100644
index 00000000..6f2bdeb9
--- /dev/null
+++ b/packages/audio_service/pubspec.yaml
@@ -0,0 +1,67 @@
+name: audio_service
+description: Flutter plugin to play audio in the background while the screen is off.
+version: 0.18.18
+repository: https://github.com/ryanheise/audio_service/tree/minor/audio_service
+issue_tracker: https://github.com/ryanheise/audio_service/issues
+topics:
+ - audio
+ - background
+
+environment:
+ sdk: ^3.6.0
+ flutter: ">=3.27.0"
+
+dependencies:
+ # Use these deps for local development
+ # audio_service_platform_interface:
+ # path: ../audio_service_platform_interface
+ # audio_service_web:
+ # path: ../audio_service_web
+
+ # Use these deps when pushing to origin (for the benefit of testers)
+ # audio_service_platform_interface:
+ # git:
+ # url: https://github.com/ryanheise/audio_service.git
+ # ref: one-isolate
+ # path: audio_service_platform_interface
+ # audio_service_web:
+ # git:
+ # url: https://github.com/ryanheise/audio_service.git
+ # ref: one-isolate
+ # path: audio_service_web
+
+ # Use these deps when publishing.
+ audio_service_platform_interface: ^0.1.3
+ audio_service_web: ^0.1.4
+
+ audio_session: '>=0.1.25 <0.3.0'
+ rxdart: '>=0.26.0 <0.29.0'
+ flutter_cache_manager: ^3.3.1
+ clock: ^1.1.0
+ js: '>=0.6.3 <0.8.0'
+ flutter:
+ sdk: flutter
+ flutter_web_plugins:
+ sdk: flutter
+
+dev_dependencies:
+ flutter_test:
+ sdk: flutter
+ mockito: ^5.0.0
+ fake_async: ^1.2.0
+ flutter_lints: ^3.0.1
+
+flutter:
+ plugin:
+ platforms:
+ android:
+ package: com.ryanheise.audioservice
+ pluginClass: AudioServicePlugin
+ ios:
+ pluginClass: AudioServicePlugin
+ sharedDarwinSource: true
+ macos:
+ pluginClass: AudioServicePlugin
+ sharedDarwinSource: true
+ web:
+ default_package: audio_service_web
diff --git a/packages/audio_service/test/audio_service_test.dart b/packages/audio_service/test/audio_service_test.dart
new file mode 100644
index 00000000..48fd4938
--- /dev/null
+++ b/packages/audio_service/test/audio_service_test.dart
@@ -0,0 +1,204 @@
+import 'package:audio_service/audio_service.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:rxdart/rxdart.dart';
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ group('BaseAudioHandler:', () {
+ test('Constructor sets correct default parameter values', () {
+ final audioHandler = BaseAudioHandler();
+
+ final actual = audioHandler.playbackState.nvalue!;
+ final expected = PlaybackState(updateTime: actual.updateTime);
+ expect(actual, equals(expected));
+ final timeNow = DateTime.now().millisecond;
+ expect(actual.updateTime.millisecond, closeTo(timeNow, 1000));
+
+ final queue = audioHandler.queue.nvalue;
+ expect(queue, equals(<MediaItem>[]));
+
+ final queueTitle = audioHandler.queueTitle.nvalue;
+ expect(queueTitle, equals(''));
+
+ final mediaItem = audioHandler.mediaItem.nvalue;
+ expect(mediaItem, isNull);
+
+ final androidPlaybackInfo = audioHandler.androidPlaybackInfo;
+ expect(androidPlaybackInfo, isA<BehaviorSubject<AndroidPlaybackInfo>>());
+
+ final ratingStyle = audioHandler.ratingStyle;
+ expect(ratingStyle, isA<BehaviorSubject<RatingStyle>>());
+
+ final customEvent = audioHandler.customEvent;
+ expect(customEvent, isA<PublishSubject<dynamic>>());
+
+ final customState = audioHandler.customState;
+ expect(customState, isA<BehaviorSubject<dynamic>>());
+ });
+
+ test('click() default logic works', () async {
+ final audioHandler = _TestableBaseAudioHandler();
+
+ // was paused, MediaButton.media clicked
+ await audioHandler.click();
+ expect(audioHandler.playbackState.nvalue!.playing, false);
+ expect(audioHandler.playCount, equals(1));
+ expect(audioHandler.pauseCount, equals(0));
+ expect(audioHandler.skipToNextCount, equals(0));
+ expect(audioHandler.skipToPreviousCount, equals(0));
+
+ // was playing, MediaButton.media clicked
+ audioHandler.reset();
+ audioHandler.playbackState.add(PlaybackState(playing: true));
+ await audioHandler.click();
+ expect(audioHandler.playCount, equals(0));
+ expect(audioHandler.pauseCount, equals(1));
+ expect(audioHandler.skipToNextCount, equals(0));
+ expect(audioHandler.skipToPreviousCount, equals(0));
+
+ // MediaButton.next
+ audioHandler.reset();
+ await audioHandler.click(MediaButton.next);
+ expect(audioHandler.playCount, equals(0));
+ expect(audioHandler.pauseCount, equals(0));
+ expect(audioHandler.skipToNextCount, equals(1));
+ expect(audioHandler.skipToPreviousCount, equals(0));
+
+ // MediaButton.previous
+ audioHandler.reset();
+ await audioHandler.click(MediaButton.previous);
+ expect(audioHandler.playCount, equals(0));
+ expect(audioHandler.pauseCount, equals(0));
+ expect(audioHandler.skipToNextCount, equals(0));
+ expect(audioHandler.skipToPreviousCount, equals(1));
+ });
+
+ test('other methods return expected default values', () async {
+ final audioHandler = BaseAudioHandler();
+
+ await audioHandler.stop();
+ expect(audioHandler.playbackState.nvalue!.processingState,
+ AudioProcessingState.idle);
+
+ final children = await audioHandler.getChildren('parentMediaId');
+ expect(children, equals(<MediaItem>[]));
+
+ final mediaItem = await audioHandler.getMediaItem('mediaId');
+ expect(mediaItem, isNull);
+
+ final results = await audioHandler.search('query');
+ expect(results, equals(<MediaItem>[]));
+ });
+ });
+
+ group('QueueHandler:', () {
+ test('able to modify media items in queue', () {
+ // setup
+ final handler = _TestableQueueHandler();
+ const mediaItem = MediaItem(id: '0', title: 'title');
+
+ // add single item
+ expect(handler.queue.nvalue?.length, equals(0));
+ handler.addQueueItem(mediaItem);
+ expect(handler.queue.nvalue?.length, equals(1));
+
+ // add multiple items
+ handler.addQueueItems([
+ mediaItem.copyWith(id: '1'),
+ mediaItem.copyWith(id: '2'),
+ ]);
+ expect(handler.queue.nvalue?.length, equals(3));
+
+ // insert item
+ handler.insertQueueItem(1, mediaItem.copyWith(id: 'inserted'));
+ expect(handler.queue.nvalue?.length, equals(4));
+ expect(handler.queue.nvalue?[1].id, 'inserted');
+
+ // update item
+ expect(handler.queue.nvalue?[0].id, '0');
+ expect(handler.queue.nvalue?[0].album, null);
+ handler.updateMediaItem(mediaItem.copyWith(album: 'abc'));
+ expect(handler.queue.nvalue?.length, equals(4));
+ expect(handler.queue.nvalue?[0].id, '0');
+ expect(handler.queue.nvalue?[0].album, 'abc');
+
+ // remove item
+ handler.removeQueueItem(mediaItem);
+ expect(handler.queue.nvalue?.length, equals(3));
+
+ // replace queue
+ handler.updateQueue([mediaItem]);
+ expect(handler.queue.nvalue?.length, equals(1));
+ });
+
+ test('skipping works', () async {
+ final handler = _TestableQueueHandler();
+ const mediaItem1 = MediaItem(id: '1', title: 'title');
+ const mediaItem2 = MediaItem(id: '2', title: 'title');
+ handler.addQueueItems([mediaItem1, mediaItem2]);
+
+ await handler.skipToQueueItem(0);
+ expect(handler.mediaItem.nvalue, equals(mediaItem1));
+
+ await handler.skipToNext();
+ expect(handler.mediaItem.nvalue, equals(mediaItem2));
+
+ await handler.skipToPrevious();
+ expect(handler.mediaItem.nvalue, equals(mediaItem1));
+ });
+ });
+}
+
+class _TestableBaseAudioHandler extends BaseAudioHandler {
+ var pauseCount = 0;
+ var playCount = 0;
+ var skipToNextCount = 0;
+ var skipToPreviousCount = 0;
+
+ void reset() {
+ pauseCount = 0;
+ playCount = 0;
+ skipToNextCount = 0;
+ skipToPreviousCount = 0;
+ }
+
+ @override
+ Future<void> pause() {
+ pauseCount++;
+ return super.pause();
+ }
+
+ @override
+ Future<void> play() {
+ playCount++;
+ return super.play();
+ }
+
+ @override
+ Future<void> skipToNext() {
+ skipToNextCount++;
+ return super.skipToNext();
+ }
+
+ @override
+ Future<void> skipToPrevious() {
+ skipToPreviousCount++;
+ return super.skipToPrevious();
+ }
+}
+
+class _TestableQueueHandler extends BaseAudioHandler with QueueHandler {
+ @override
+ Future<void> skipToQueueItem(int index) async {
+ playbackState.add(playbackState.nvalue!.copyWith(queueIndex: index));
+ mediaItem.add(queue.nvalue![index]);
+ await super.skipToQueueItem(index);
+ }
+}
+
+/// Backwards compatible extensions on rxdart's ValueStream
+extension _ValueStreamExtension<T> on ValueStream<T> {
+ /// Backwards compatible version of valueOrNull.
+ T? get nvalue => hasValue ? value : null;
+}
diff --git a/packages/audio_service/test/data_classes_test.dart b/packages/audio_service/test/data_classes_test.dart
new file mode 100644
index 00000000..7b9583da
--- /dev/null
+++ b/packages/audio_service/test/data_classes_test.dart
@@ -0,0 +1,374 @@
+import 'package:audio_service/audio_service.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:fake_async/fake_async.dart';
+
+const asciiSquare = '▮';
+
+void main() {
+ group('$PlaybackState $asciiSquare', () {
+ // Set initial values for nullable parameters
+ final state = PlaybackState(
+ androidCompactActionIndices: const [2, 3],
+ errorCode: 0,
+ errorMessage: 'errorMessage',
+ queueIndex: 0,
+ );
+
+ test('position getter', () {
+ fakeAsync((async) {
+ const duration = Duration(milliseconds: 550);
+
+ var localState = PlaybackState(
+ processingState: AudioProcessingState.ready,
+ playing: true,
+ );
+ async.elapse(duration);
+ expect(localState.position, duration);
+
+ const speed = 2.0;
+ localState = localState.copyWith(speed: speed);
+ async.elapse(duration);
+ expect(
+ localState.position,
+ Duration(milliseconds: (duration.inMilliseconds * speed).toInt()),
+ );
+
+ // Playing set to false or not [AudioProcessingState.ready] should
+ // return the [updatePosition]
+ localState = localState.copyWith(playing: false);
+ async.elapse(duration);
+ expect(state.position, Duration.zero);
+
+ localState = localState.copyWith(
+ playing: true,
+ processingState: AudioProcessingState.buffering,
+ );
+ async.elapse(duration);
+ expect(state.position, Duration.zero);
+ });
+ });
+
+ test('throws with invalid `androidCompactActionIndices`', () {
+ expect(
+ () => PlaybackState(androidCompactActionIndices: [1, 2, 3, 4]),
+ throwsAssertionError,
+ );
+ });
+
+ test('equality', () {
+ fakeAsync((async) {
+ expect(
+ PlaybackState(
+ controls: [MediaControl.play],
+ androidCompactActionIndices: [1, 2, 3],
+ systemActions: {MediaAction.fastForward},
+ ),
+ PlaybackState(
+ controls: [MediaControl.play],
+ androidCompactActionIndices: [1, 2, 3],
+ systemActions: {MediaAction.fastForward},
+ ),
+ );
+ expect(
+ PlaybackState(controls: [MediaControl.pause]),
+ isNot(PlaybackState(controls: [MediaControl.play])),
+ );
+ });
+ });
+
+ test('empty copyWith does nothing', () {
+ final actual = state.copyWith();
+ expect(
+ actual,
+ PlaybackState(
+ androidCompactActionIndices: const [2, 3],
+ updateTime: actual.updateTime,
+ errorCode: 0,
+ errorMessage: 'errorMessage',
+ queueIndex: 0,
+ ),
+ );
+ });
+
+ test('copyWith works', () {
+ final actual = state.copyWith(
+ processingState: AudioProcessingState.buffering,
+ playing: true,
+ controls: const [MediaControl.play],
+ androidCompactActionIndices: null,
+ systemActions: const {MediaAction.fastForward},
+ updatePosition: const Duration(seconds: 1),
+ bufferedPosition: const Duration(seconds: 1),
+ speed: 2.0,
+ errorCode: null,
+ errorMessage: null,
+ repeatMode: AudioServiceRepeatMode.one,
+ shuffleMode: AudioServiceShuffleMode.all,
+ captioningEnabled: false,
+ queueIndex: null,
+ );
+
+ // Verify that nullable values can be nulled out,
+ // other values can be changed
+ expect(
+ actual,
+ PlaybackState(
+ processingState: AudioProcessingState.buffering,
+ playing: true,
+ controls: const [MediaControl.play],
+ androidCompactActionIndices: null,
+ systemActions: const {MediaAction.fastForward},
+ updatePosition: const Duration(seconds: 1),
+ bufferedPosition: const Duration(seconds: 1),
+ speed: 2.0,
+ updateTime: actual.updateTime,
+ errorCode: null,
+ errorMessage: null,
+ repeatMode: AudioServiceRepeatMode.one,
+ shuffleMode: AudioServiceShuffleMode.all,
+ captioningEnabled: false,
+ queueIndex: null,
+ ),
+ );
+ });
+ });
+
+ group('$Rating $asciiSquare', () {
+ test('equality', () {
+ expect(
+ Rating.newStarRating(RatingStyle.range3stars, 3),
+ Rating.newStarRating(RatingStyle.range3stars, 3),
+ );
+ expect(
+ Rating.newStarRating(RatingStyle.range3stars, 3),
+ isNot(const Rating.newPercentageRating(3)),
+ );
+ });
+
+ test('percentage style', () {
+ // not percentage style should return -1
+ expect(
+ const Rating.newHeartRating(false).getPercentRating(),
+ -1,
+ );
+ // unset rating should return -1
+ expect(
+ const Rating.newUnratedRating(RatingStyle.percentage)
+ .getPercentRating(),
+ -1,
+ );
+ // invalid values throw
+ expect(
+ () => Rating.newPercentageRating(-1),
+ throwsAssertionError,
+ );
+ expect(
+ () => Rating.newPercentageRating(101),
+ throwsAssertionError,
+ );
+ // should return a valid value otherwise
+ expect(
+ const Rating.newPercentageRating(100).getPercentRating(),
+ 100,
+ );
+ });
+
+ test('star style', () {
+ // not star style should return -1
+ expect(
+ const Rating.newHeartRating(false).getStarRating(),
+ -1,
+ );
+ // unset rating should return -1
+ expect(
+ const Rating.newUnratedRating(RatingStyle.range3stars).getStarRating(),
+ -1,
+ );
+ // invalid values throw
+ expect(
+ () => Rating.newStarRating(RatingStyle.heart, 0),
+ throwsAssertionError,
+ );
+ expect(
+ () => Rating.newStarRating(RatingStyle.range3stars, 4),
+ throwsAssertionError,
+ );
+ expect(
+ () => Rating.newStarRating(RatingStyle.range4stars, 5),
+ throwsAssertionError,
+ );
+ expect(
+ () => Rating.newStarRating(RatingStyle.range5stars, 6),
+ throwsAssertionError,
+ );
+ // should return a valid value otherwise
+ expect(
+ Rating.newStarRating(RatingStyle.range3stars, 3).getStarRating(),
+ 3,
+ );
+ });
+
+ test('heart style', () {
+ // not heart style should return false
+ expect(
+ const Rating.newPercentageRating(0).hasHeart(),
+ false,
+ );
+ // unset rating should return false
+ expect(
+ const Rating.newUnratedRating(RatingStyle.heart).hasHeart(),
+ false,
+ );
+ // should return a valid value otherwise
+ expect(
+ const Rating.newHeartRating(true).hasHeart(),
+ true,
+ );
+ });
+
+ test('thumb style', () {
+ // not thumb style should return false
+ expect(
+ const Rating.newPercentageRating(0).isThumbUp(),
+ false,
+ );
+ // unset rating should return false
+ expect(
+ const Rating.newUnratedRating(RatingStyle.thumbUpDown).isThumbUp(),
+ false,
+ );
+ // should return a valid value otherwise
+ expect(
+ const Rating.newThumbRating(true).isThumbUp(),
+ true,
+ );
+ });
+
+ test('is rated', () {
+ expect(
+ const Rating.newUnratedRating(RatingStyle.percentage).isRated(),
+ false,
+ );
+ expect(
+ const Rating.newPercentageRating(0).isRated(),
+ true,
+ );
+ });
+ });
+
+ group('$MediaItem $asciiSquare', () {
+ // Set initial values for nullable parameters
+ final mediaItem = MediaItem(
+ id: 'id',
+ title: 'title',
+ album: 'album',
+ artist: 'artist',
+ genre: 'genre',
+ duration: const Duration(seconds: 1),
+ artUri: Uri.file('file'),
+ playable: true,
+ displayTitle: 'displayTitle',
+ displaySubtitle: 'displaySubtitle',
+ displayDescription: 'displayDescription',
+ rating: const Rating.newHeartRating(false),
+ extras: <String, dynamic>{'key': 'value'},
+ );
+
+ test('equality', () {
+ expect(
+ mediaItem,
+ const MediaItem(id: 'id', title: 'title'),
+ );
+ expect(
+ mediaItem,
+ const MediaItem(id: 'id', title: 'otherTitle'),
+ );
+ expect(
+ mediaItem,
+ isNot(const MediaItem(id: 'otherId', title: 'title')),
+ );
+ });
+
+ test('empty copyWith does nothing', () {
+ final actual = mediaItem.copyWith();
+ expect(actual, mediaItem);
+ });
+
+ test('copyWith works', () {
+ final actual = mediaItem.copyWith(
+ id: '_id',
+ title: '_title',
+ album: null,
+ artist: null,
+ genre: null,
+ duration: null,
+ artUri: null,
+ playable: null,
+ displayTitle: null,
+ displaySubtitle: null,
+ displayDescription: null,
+ rating: null,
+ extras: null,
+ );
+
+ // Verify that nullable values can be nulled out,
+ // other values can be changed
+ expect(
+ actual,
+ const MediaItem(
+ id: '_id',
+ title: '_title',
+ album: null,
+ artist: null,
+ genre: null,
+ duration: null,
+ artUri: null,
+ playable: null,
+ displayTitle: null,
+ displaySubtitle: null,
+ displayDescription: null,
+ rating: null,
+ extras: null,
+ ),
+ );
+ });
+ });
+
+ group('$MediaControl $asciiSquare', () {
+ const mediaControl = MediaControl(
+ androidIcon: 'androidIcon',
+ label: 'label',
+ action: MediaAction.pause,
+ );
+
+ test('equality', () {
+ expect(
+ mediaControl,
+ // ignore: prefer_const_constructors
+ MediaControl(
+ androidIcon: 'androidIcon',
+ label: 'label',
+ action: MediaAction.pause,
+ ),
+ );
+ expect(
+ mediaControl,
+ isNot(MediaControl.pause),
+ );
+ });
+ });
+
+ group('$AudioServiceConfig $asciiSquare', () {
+ test('asserts proper notification ongoing config', () {
+ expect(
+ () {
+ AudioServiceConfig(
+ androidNotificationOngoing: true,
+ androidStopForegroundOnPause: false,
+ );
+ },
+ throwsAssertionError,
+ );
+ });
+ });
+}
diff --git a/packages/audio_service/test/isolates_test.dart b/packages/audio_service/test/isolates_test.dart
new file mode 100644
index 00000000..e8c99983
--- /dev/null
+++ b/packages/audio_service/test/isolates_test.dart
@@ -0,0 +1,370 @@
+// ignore_for_file: close_sinks
+
+import 'dart:isolate';
+
+import 'package:audio_service/audio_service.dart';
+import 'package:fake_async/fake_async.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:rxdart/rxdart.dart';
+
+Isolate? isolate;
+
+class Data {
+ static final playbackState = PlaybackState(
+ processingState: AudioProcessingState.buffering,
+ playing: true,
+ controls: [MediaControl.pause],
+ androidCompactActionIndices: [0],
+ systemActions: {MediaAction.seek},
+ updatePosition: const Duration(seconds: 30),
+ bufferedPosition: const Duration(seconds: 35),
+ speed: 1.5,
+ updateTime: DateTime.now(),
+ errorCode: 3,
+ errorMessage: 'error message',
+ repeatMode: AudioServiceRepeatMode.all,
+ shuffleMode: AudioServiceShuffleMode.all,
+ captioningEnabled: true,
+ queueIndex: 0,
+ );
+ static final playbackStates = [
+ PlaybackState(playing: true),
+ PlaybackState(processingState: AudioProcessingState.buffering),
+ PlaybackState(speed: 1.5),
+ ];
+ static const query = 'query';
+ static final uri = Uri.parse('https://example.com/foo');
+ static const mediaId = '1';
+ static const mediaItem = MediaItem(id: '1', title: 'title1');
+ static final mediaItems = [
+ const MediaItem(id: '1', title: 'title1'),
+ const MediaItem(id: '2', title: 'title2'),
+ const MediaItem(id: '3', title: 'title3'),
+ ];
+ static final remotePlaybackInfo = RemoteAndroidPlaybackInfo(
+ volumeControlType: AndroidVolumeControlType.absolute,
+ maxVolume: 10,
+ volume: 5,
+ );
+}
+
+void main() {
+ group('isolates', () {
+ late AudioHandler proxy;
+
+ late bool spawningIsolate;
+
+ setUp(() async {
+ if (spawningIsolate) {
+ await runIsolateHandler();
+ } else {
+ IsolatedAudioHandler(_MockAudioHandler());
+ }
+ proxy = await IsolatedAudioHandler.lookup();
+ });
+
+ tearDown(() async {
+ await proxy.unregister();
+ if (spawningIsolate) {
+ await killIsolate();
+ }
+ });
+
+ // We need to run the tests not only in different isolates but also in the
+ // same isolate since coverage is only collected by the main isolate:
+ // https://github.com/dart-lang/test/issues/1108
+ for (var differentIsolate in [true, false]) {
+ spawningIsolate = differentIsolate;
+ final isolateLabel =
+ differentIsolate ? ' (different isolate)' : ' (same isolate)';
+
+ test('init $isolateLabel', () async {
+ final playbackState = await proxy.playbackState.first;
+ fakeAsync((async) {
+ // ignore the updateTime
+ expect(playbackState.copyWith(), PlaybackState());
+ });
+ expect(await proxy.queue.first, const <MediaItem>[]);
+ expect(await proxy.queueTitle.first, '');
+ expect(await proxy.mediaItem.first, null);
+ expect(proxy.ratingStyle.hasValue, false);
+ expect(proxy.androidPlaybackInfo.hasValue, false);
+ expect(proxy.customState.hasValue, false);
+ });
+
+ test('method invocations $isolateLabel', () async {
+ Future<void> testMethod(String method, dynamic Function() function,
+ {dynamic expectedResult}) async {
+ final startCount = await proxy.count(method);
+ final dynamic result = await function();
+ expect(await proxy.count(method), startCount + 1);
+ if (expectedResult != null) {
+ expect(result, expectedResult);
+ }
+ }
+
+ await testMethod('prepare', () => proxy.prepare());
+ await testMethod('prepareFromMediaId',
+ () => proxy.prepareFromMediaId('1', <String, dynamic>{}));
+ await testMethod('prepareFromSearch',
+ () => proxy.prepareFromSearch(Data.query, <String, dynamic>{}));
+ await testMethod('prepareFromUri',
+ () => proxy.prepareFromUri(Data.uri, <String, dynamic>{}));
+ await testMethod('play', () => proxy.play());
+ await testMethod('playFromMediaId',
+ () => proxy.playFromMediaId(Data.mediaId, <String, dynamic>{}));
+ await testMethod('playFromSearch',
+ () => proxy.playFromSearch(Data.query, <String, dynamic>{}));
+ await testMethod('playFromUri',
+ () => proxy.playFromUri(Data.uri, <String, dynamic>{}));
+ await testMethod(
+ 'playMediaItem', () => proxy.playMediaItem(Data.mediaItem));
+ await testMethod('pause', () => proxy.pause());
+ await testMethod('click', () => proxy.click());
+ await testMethod('stop', () => proxy.stop());
+ await testMethod(
+ 'addQueueItem', () => proxy.addQueueItem(Data.mediaItem));
+ await testMethod(
+ 'addQueueItems', () => proxy.addQueueItems(Data.mediaItems));
+ await testMethod(
+ 'insertQueueItem', () => proxy.insertQueueItem(0, Data.mediaItem));
+ await testMethod(
+ 'updateQueue', () => proxy.updateQueue(Data.mediaItems));
+ await testMethod(
+ 'updateMediaItem', () => proxy.updateMediaItem(Data.mediaItem));
+ await testMethod(
+ 'removeQueueItem', () => proxy.removeQueueItem(Data.mediaItem));
+ await testMethod('removeQueueItemAt', () => proxy.removeQueueItemAt(0));
+ await testMethod('skipToNext', () => proxy.skipToNext());
+ await testMethod('skipToPrevious', () => proxy.skipToPrevious());
+ await testMethod('fastForward', () => proxy.fastForward());
+ await testMethod('rewind', () => proxy.rewind());
+ await testMethod('skipToQueueItem', () => proxy.skipToQueueItem(0));
+ await testMethod('seek', () => proxy.seek(Duration.zero));
+ await testMethod(
+ 'setRating',
+ () => proxy.setRating(
+ const Rating.newHeartRating(true), <String, dynamic>{}));
+ await testMethod(
+ 'setCaptioningEnabled', () => proxy.setCaptioningEnabled(true));
+ await testMethod('setRepeatMode',
+ () => proxy.setRepeatMode(AudioServiceRepeatMode.all));
+ await testMethod('setShuffleMode',
+ () => proxy.setShuffleMode(AudioServiceShuffleMode.all));
+ await testMethod('seekBackward', () => proxy.seekBackward(true));
+ await testMethod('seekForward', () => proxy.seekForward(true));
+ await testMethod('setSpeed', () => proxy.setSpeed(1.5));
+ await testMethod('onTaskRemoved', () => proxy.onTaskRemoved());
+ await testMethod(
+ 'onNotificationDeleted', () => proxy.onNotificationDeleted());
+ await testMethod('getChildren',
+ () => proxy.getChildren(Data.mediaId, <String, dynamic>{}),
+ expectedResult: Data.mediaItems);
+ await testMethod('subscribeToChildren',
+ () => proxy.subscribeToChildren(Data.mediaId));
+ await testMethod('getMediaItem', () => proxy.getMediaItem(Data.mediaId),
+ expectedResult: Data.mediaItem);
+ await testMethod(
+ 'search', () => proxy.search(Data.query, <String, dynamic>{}),
+ expectedResult: Data.mediaItems);
+ await testMethod(
+ 'androidSetRemoteVolume', () => proxy.androidSetRemoteVolume(3));
+ await testMethod(
+ 'androidAdjustRemoteVolume',
+ () =>
+ proxy.androidAdjustRemoteVolume(AndroidVolumeDirection.raise));
+ await testMethod('customAction',
+ () => proxy.customAction('echo', <String, dynamic>{'arg': 'foo'}),
+ expectedResult: 'foo');
+ await testMethod('customAction',
+ () => proxy.customAction('echo', <String, dynamic>{'arg': 'bar'}),
+ expectedResult: 'bar');
+ });
+
+ test('stream values $isolateLabel', () async {
+ Future<void> testStream<T>(
+ String name, ValueStream<T> stream, T value) async {
+ await proxy.add(name, value);
+ expect(stream.nvalue, value);
+ }
+
+ await testStream(
+ 'playbackState', proxy.playbackState, Data.playbackState);
+ await testStream('queue', proxy.queue, Data.mediaItems);
+ await testStream('queueTitle', proxy.queueTitle, 'Queue');
+ await testStream('androidPlaybackInfo', proxy.androidPlaybackInfo,
+ Data.remotePlaybackInfo);
+ await testStream('ratingStyle', proxy.ratingStyle, RatingStyle.heart);
+ await testStream<dynamic>('customState', proxy.customState, 'foo');
+ });
+
+ test('streams $isolateLabel', () async {
+ Future<void> testStream<T>(String name, Stream<T> stream,
+ bool skipFirst, List<T> values) async {
+ final actualValues = <T>[];
+ final subscription =
+ stream.skip(skipFirst ? 1 : 0).listen(actualValues.add);
+ for (var value in values) {
+ await proxy.add(name, value);
+ }
+ expect(actualValues, values);
+ subscription.cancel();
+ }
+
+ await testStream(
+ 'playbackState', proxy.playbackState, true, Data.playbackStates);
+ await testStream('queue', proxy.queue, true, [
+ Data.mediaItems,
+ Data.mediaItems
+ .map((item) =>
+ item.copyWith(displayDescription: '${item.id} description'))
+ .toList(),
+ ]);
+ await testStream('queueTitle', proxy.queueTitle, true, ['a', 'b', 'c']);
+ await testStream('mediaItem', proxy.mediaItem, true, Data.mediaItems);
+ await testStream(
+ 'androidPlaybackInfo', proxy.androidPlaybackInfo, false, [
+ Data.remotePlaybackInfo,
+ LocalAndroidPlaybackInfo(),
+ ]);
+ await testStream('ratingStyle', proxy.ratingStyle, false, [
+ RatingStyle.heart,
+ RatingStyle.percentage,
+ ]);
+ await testStream<dynamic>(
+ 'customEvent', proxy.customEvent, false, <dynamic>[
+ 'a',
+ 'b',
+ 'c',
+ ]);
+ await testStream<dynamic>(
+ 'customState', proxy.customState, false, <dynamic>[
+ 'a',
+ 'b',
+ 'c',
+ ]);
+ });
+ }
+ });
+}
+
+Future<void> runIsolateHandler() async {
+ final receivePort = ReceivePort();
+ isolate = await Isolate.spawn(isolateEntryPoint, receivePort.sendPort);
+ final success = (await receivePort.first) as bool;
+ assert(success);
+}
+
+Future<void> killIsolate() async {
+ isolate!.kill();
+ isolate = null;
+}
+
+void isolateEntryPoint(SendPort sendPort) {
+ IsolatedAudioHandler(_MockAudioHandler());
+ sendPort.send(true);
+}
+
+class _MockAudioHandler implements BaseAudioHandler {
+ @override
+ final BehaviorSubject<PlaybackState> playbackState =
+ BehaviorSubject.seeded(PlaybackState());
+
+ @override
+ final BehaviorSubject<List<MediaItem>> queue =
+ BehaviorSubject.seeded(<MediaItem>[]);
+
+ @override
+ final BehaviorSubject<String> queueTitle = BehaviorSubject.seeded('');
+
+ @override
+ final BehaviorSubject<MediaItem?> mediaItem = BehaviorSubject.seeded(null);
+
+ @override
+ final BehaviorSubject<AndroidPlaybackInfo> androidPlaybackInfo =
+ BehaviorSubject();
+
+ @override
+ final BehaviorSubject<RatingStyle> ratingStyle = BehaviorSubject();
+
+ @override
+ final PublishSubject<dynamic> customEvent = PublishSubject<dynamic>();
+
+ @override
+ final BehaviorSubject<dynamic> customState = BehaviorSubject<dynamic>();
+
+ final Map<String, int> invocationCounts = {};
+
+ @override
+ dynamic noSuchMethod(Invocation invocation) {
+ final member = invocation.memberName.toString().split('"')[1];
+ if (invocation.isMethod) {
+ if (member != 'customAction' ||
+ invocation.positionalArguments[0] != 'count') {
+ // count invocations of everything except for 'count' itself.
+ invocationCounts[member] = (invocationCounts[member] ?? 0) + 1;
+ }
+ switch (member) {
+ case 'customAction':
+ return _handleCustomAction(invocation);
+ case 'getChildren':
+ case 'search':
+ return Future.value(Data.mediaItems);
+ case 'subscribeToChildren':
+ return BehaviorSubject.seeded(<String, dynamic>{});
+ case 'getMediaItem':
+ return Future.value(Data.mediaItem);
+ default:
+ return Future.value(null);
+ }
+ }
+ return super.noSuchMethod(invocation);
+ }
+
+ Future<dynamic> _handleCustomAction(Invocation invocation) async {
+ final args = invocation.positionalArguments;
+ final name = args[0] as String;
+ final extras = args[1] as Map<String, dynamic>?;
+ switch (name) {
+ case 'count':
+ final method = extras!['method'] as String;
+ return invocationCounts[method] ?? 0;
+ case 'echo':
+ return extras!['arg'] as String;
+ case 'add':
+ final streamName = extras!['stream'] as String;
+ final dynamic arg = extras['arg'];
+ <String, Subject<dynamic>>{
+ 'playbackState': playbackState,
+ 'queue': queue,
+ 'queueTitle': queueTitle,
+ 'mediaItem': mediaItem,
+ 'androidPlaybackInfo': androidPlaybackInfo,
+ 'ratingStyle': ratingStyle,
+ 'customEvent': customEvent,
+ 'customState': customState,
+ }[streamName]!
+ .add(arg);
+ break;
+ }
+ }
+}
+
+extension AudioHandlerExtension on AudioHandler {
+ Future<int> count(String method) async =>
+ (await customAction('count', <String, dynamic>{'method': method}) as int);
+
+ Future<String> echo(String arg) async =>
+ (await customAction('echo', <String, dynamic>{'arg': arg}) as String);
+
+ Future<void> add(String stream, dynamic arg) =>
+ customAction('add', <String, dynamic>{'stream': stream, 'arg': arg});
+
+ Future<void> unregister() => customAction('unregister');
+}
+
+/// Backwards compatible extensions on rxdart's ValueStream
+extension _ValueStreamExtension<T> on ValueStream<T> {
+ /// Backwards compatible version of valueOrNull.
+ T? get nvalue => hasValue ? value : null;
+}
diff --git a/pubspec.lock b/pubspec.lock
index 3e93a674..40ec7cbc 100644
--- a/pubspec.lock
+++ b/pubspec.lock
@@ -36,10 +36,9 @@ packages:
audio_service:
dependency: "direct main"
description:
- name: audio_service
- sha256: cb122c7c2639d2a992421ef96b67948ad88c5221da3365ccef1031393a76e044
- url: "https://pub.dev"
- source: hosted
+ path: "packages/audio_service"
+ relative: true
+ source: path
version: "0.18.18"
audio_service_platform_interface:
dependency: transitive
diff --git a/pubspec.yaml b/pubspec.yaml
index 9513dd01..0e36b8d5 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -36,7 +36,8 @@ dependencies:
just_audio:
path: packages/just_audio
- audio_service: ^0.18.13
+ audio_service:
+ path: packages/audio_service
# CarPlay
flutter_carplay: ^1.2.11