# audio_service
This plugin wraps around your existing audio code to allow it to run in the background or with the screen turned off, and allows your app to interact with headset buttons, the Android lock screen and notification, iOS control center, wearables and Android Auto. It is suitable for:
* Music players
* Text-to-speech readers
* Podcast players
* Video players
* Navigators
* More!
## How does this plugin work?
You encapsulate your audio code in a background task which runs in a special isolate that continues to run when your UI is absent. Your background task implements callbacks to respond to playback requests coming from your Flutter UI, headset buttons, the lock screen, notification, iOS control center, car displays and smart watches:
![audio_service_callbacks](https://user-images.githubusercontent.com/19899190/84386442-b305cc80-ac34-11ea-8c2f-1b4cb126a98d.png)
You can implement these callbacks to play any sort of audio that is appropriate for your app, such as music files or streams, audio assets, text to speech, synthesised audio, or combinations of these.
| Feature | Android | iOS | macOS | Web |
| ------- | :-------: | :-----: | :-----: | :-----: |
| background audio | ✅ | ✅ | ✅ | ✅ |
| headset clicks | ✅ | ✅ | ✅ | ✅ |
| start/stop/play/pause/seek/rate | ✅ | ✅ | ✅ | ✅ |
| fast forward/rewind | ✅ | ✅ | ✅ | ✅ |
| repeat/shuffle mode | ✅ | ✅ | ✅ | ✅ |
| queue manipulation, skip next/prev | ✅ | ✅ | ✅ | ✅ |
| custom actions | ✅ | ✅ | ✅ | ✅ |
| custom events | ✅ | ✅ | ✅ | ✅ |
| notifications/control center | ✅ | ✅ | ✅ | ✅ |
| lock screen controls | ✅ | ✅ | | ✅ |
| album art | ✅ | ✅ | ✅ | ✅ |
| Android Auto, Apple CarPlay | (untested) | ✅ | | |
If you'd like to help with any missing features, please join us on the [GitHub issues page](https://github.com/ryanheise/audio_service/issues).
## Preview the upcoming 0.18.0 release
A new version of audio_service is around the corner. This version removes the need for a background isolate, allowing simpler communication between your UI and audio logic, and greater compatibility with plugins that don't support multiple isolates.
If you are interested to help with testing or providing feedback, you can upgrade by following the instructions in the [Migration Guide](https://github.com/ryanheise/audio_service/wiki/Migration-Guide#0180-preview).
## Can I make use of other plugins within the background audio task?
Yes! `audio_service` is designed to let you implement the audio logic however you want, using whatever plugins you want. You can use your favourite audio plugins such as [just_audio](https://pub.dartlang.org/packages/just_audio), [flutter_radio](https://pub.dev/packages/flutter_radio), [flutter_tts](https://pub.dartlang.org/packages/flutter_tts), and others, within your background audio task. There are also plugins like [just_audio_service](https://github.com/yringler/just_audio_service) that provide default implementations of `BackgroundAudioTask` to make your job easier.
Note that this plugin will not work with other audio plugins that overlap in responsibility with this plugin (i.e. background audio, iOS control center, Android notifications, lock screen, headset buttons, etc.)
## Example
### UI code
Wrap your `/` route's widget tree in an `AudioServiceWidget`:
```dart
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Audio Service Demo',
home: AudioServiceWidget(child: MainScreen()),
);
}
}
```
Start/stop your background audio task:
```dart
await AudioService.start(backgroundTaskEntrypoint: _entrypoint);
await AudioService.stop();
```
Standard controls:
```dart
AudioService.play();
AudioService.seekTo(Duration(seconds: 10));
AudioService.setSpeed(1.5);
AudioService.pause();
```
Queue management:
```dart
var item = MediaItem(
id: 'https://example.com/audio.mp3',
album: 'Album name',
title: 'Track title',
);
AudioService.addQueueItem(item);
AudioService.addQueueItemAt(item, 1);
AudioService.removeQueueItem(item);
AudioService.updateQueue([item, ...]);
AudioService.skipToNext();
AudioService.skipToPrevious();
AudioService.playFromMediaId('https://example.com/audio.mp3')
AudioService.playMediaItem(item);
```
Looping and shuffling:
```dart
AudioService.setRepeatMode(AudioServiceRepeatMode.one); // none/one/all/group
AudioService.setShuffleMode(AudioServiceShuffleMode.all); // none/all/group
```
Custom actions:
```dart
AudioService.customAction('setVolume', 0.8);
AudioService.customAction('saveBookmark');
```
Listening to state changes:
```dart
AudioService.playbackStateStream.listen((PlaybackState state) {
if (state.playing) ... else ...
switch (state.processingState) {
case AudioProcessingState.none: ...
case connecting: ...
case ready: ...
case buffering: ...
case fastForwarding: ...
case rewinding: ...
case skippingToPrevious: ...
case skippingToNext: ...
case skippingToQueueItem: ...
case completed: ...
case stopped: ...
case error: ...
}
});
```
Listen to changes to the currently playing item:
```dart
AudioService.currentMediaItemStream.listen((MediaItem item) { ... });
```
Listen to changes to the queue:
```dart
AudioService.queueStream.listen((List<MediaItem> queue) { ... });
```
Listen to changes to the current playback position:
```dart
AudioService.positionStream.listen((Duration position) { ... });
```
### Background code
Define a background audio task to handle callbacks for all methods called from your UI or other clients (e.g. the media notification):
```dart
// Must be a top-level function
void _entrypoint() => AudioServiceBackground.run(() => AudioPlayerTask());
class AudioPlayerTask extends BackgroundAudioTask {
final _player = AudioPlayer(); // e.g. just_audio
// Implement callbacks here. e.g. onStart, onStop, onPlay, onPause
}
```
The purpose of this class is to encapsulate all audio logic in your app so that it is completely self-contained, and can continue to run on its own even when the Flutter UI is not present. Every message that you send from your Flutter UI (`start`, `stop`, `play`, `pause`) has a corresponding callback that you can implement in your background audio task (`onStart`, `onStop`, `onPlay`, `onPause`). Additionally, there are callbacks that respond only to events outside of your Flutter UI, such as `onClick`, which responds to a click of a headset button, and `onClose` which responds to the user swiping away the Android media notification.
Most of these callbacks can be implemented by simply delegating to your audio player plugin:
```dart
onPlay() => _player.play();
onPause() => _player.pause();
onSeekTo(Duration duration) => _player.seekTo(duration);
onSetSpeed(double speed) => _player.setSpeed(speed);
```
Your custom actions may be handled via a switch:
```dart
onCustomAction(String name, dynamic arguments) async {
switch (name) {
case 'setVolume':
_player.setVolume(arguments);
break;
case 'saveBookmark':
// app-specific code
break;
}
}
```
`onStart` is the place to initialise the player, and (usually) start playing audio:
```dart
onStart(Map<String, dynamic> params) async {
final mediaItem = MediaItem(
id: "https://foo.bar/baz.mp3",
album: "Foo",
title: "Bar",
);
// Tell the UI and
没有合适的资源?快使用搜索试试~ 我知道了~
audio_service:Flutter 插件可在屏幕关闭时在后台播放音频
共201个文件
png:93个
xml:11个
java:8个
需积分: 32 7 下载量 197 浏览量
2021-08-04
20:32:14
上传
评论
收藏 305KB ZIP 举报
温馨提示
音频服务 此插件环绕您现有的音频代码,使其能够在后台运行或在屏幕关闭的情况下运行,并允许您的应用与耳机按钮、Android 锁屏和通知、iOS 控制中心、可穿戴设备和 Android Auto 进行交互。 它适用于: 音乐播放器 文字转语音阅读器 播客播放器 视频播放器 导航器 更多的! 这个插件是如何工作的? 您将音频代码封装在一个后台任务中,该任务在一个特殊的隔离区中运行,该隔离区在您的 UI 不存在时继续运行。 您的后台任务实现回调以响应来自 Flutter UI、耳机按钮、锁定屏幕、通知、iOS 控制中心、车载显示器和智能手表的播放请求: 您可以实现这些回调来播放适合您的应用程序的任何类型的音频,例如音乐文件或流、音频资产、文本到语音、合成音频或这些的组合。 特征 安卓 IOS 苹果系统 网络 背景音频 :check_mark_button: :check_mark_button: :check_mark_button: :check_mark_button: 耳机咔哒声 :check_mark_button: :check_mark_butto
资源推荐
资源详情
资源评论
收起资源包目录
audio_service:Flutter 插件可在屏幕关闭时在后台播放音频 (201个子文件)
audio_service.dart 74KB
audio_service_test.dart 25KB
main.dart 24KB
audio_service_web.dart 12KB
widget_test.dart 904B
media_session_web.dart 794B
DebugProfile.entitlements 406B
Release.entitlements 298B
.gitignore 1KB
.gitignore 542B
.gitignore 415B
.gitignore 399B
.gitignore 262B
.gitignore 97B
.gitignore 81B
.gitkeep 0B
build.gradle 2KB
build.gradle 679B
settings.gradle 484B
build.gradle 470B
settings.gradle 35B
AudioServicePlugin.h 958B
AudioServicePlugin.h 948B
Runner-Bridging-Header.h 37B
index.html 1KB
audio_service_android.iml 2KB
audio_service.iml 949B
AudioServicePlugin.java 47KB
AudioService.java 32KB
MediaButtonReceiver.java 687B
AudioProcessingState.java 269B
Size.java 210B
MainActivity.java 152B
AudioInterruption.java 139B
MediaControl.java 100B
Contents.json 2KB
Contents.json 1KB
manifest.json 570B
Contents.json 391B
LICENSE 1KB
Podfile.lock 2KB
Podfile.lock 2KB
AudioServicePlugin.m 26KB
AudioServicePlugin.m 41B
AudioServicePlugin.m 41B
README.md 17KB
CHANGELOG.md 6KB
bug_report.md 3KB
feature_request.md 2KB
documentation-request.md 1KB
README.md 336B
README.md 308B
.metadata 283B
project.pbxproj 26KB
project.pbxproj 23KB
Info.plist 2KB
Info.plist 1KB
AppFrameworkInfo.plist 794B
IDEWorkspaceChecks.plist 238B
IDEWorkspaceChecks.plist 238B
IDEWorkspaceChecks.plist 238B
IDEWorkspaceChecks.plist 238B
app_icon_1024.png 46KB
app_icon_512.png 14KB
Icon-App-1024x1024@1x.png 11KB
Icon-512.png 8KB
app_icon_256.png 6KB
Icon-192.png 5KB
Icon-App-60x60@3x.png 4KB
Icon-App-83.5x83.5@2x.png 4KB
Icon-App-76x76@2x.png 3KB
app_icon_128.png 3KB
Icon-App-40x40@3x.png 3KB
Icon-App-60x60@2x.png 3KB
Icon-App-29x29@3x.png 2KB
Icon-App-40x40@2x.png 2KB
Icon-App-76x76@1x.png 2KB
app_icon_64.png 2KB
Icon-App-29x29@2x.png 2KB
Icon-App-20x20@3x.png 2KB
ic_launcher.png 1KB
app_icon_16.png 1KB
Icon-App-40x40@1x.png 1KB
Icon-App-20x20@2x.png 1KB
audio_service_skip_previous.png 1KB
audio_service_skip_next.png 1KB
app_icon_32.png 1KB
audio_service_play_arrow.png 1KB
ic_launcher.png 1KB
Icon-App-29x29@1x.png 1KB
audio_service_fast_rewind.png 952B
favicon.png 917B
audio_service_skip_previous.png 857B
audio_service_fast_forward.png 838B
audio_service_skip_next.png 832B
audio_service_fast_rewind.png 770B
ic_launcher.png 721B
audio_service_play_arrow.png 720B
audio_service_fast_forward.png 684B
audio_service_skip_previous.png 639B
共 201 条
- 1
- 2
- 3
资源评论
笨猫猪
- 粉丝: 30
- 资源: 4732
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功