直接从Flutter(Android / ios / Web / MacOS)直接播放存储在资产文件中的音乐 /音频。
您还可以使用网络中的播放音频文件使用其URL,收音机/直播和本地文件
可以在Android&iOS上显示通知,并处理蓝牙操作
flutter :
assets :
- assets/audios/ AssetsAudioPlayer . newPlayer (). open (
Audio ( "assets/audios/song1.mp3" ),
autoStart : true ,
showNotification : true ,
);

dependencies :
assets_audio_player : ^3.0.8与flutter: ">=3.3.0" ,请确保升级您的SDK
你喜欢包装吗?给我买一个kofi :)
| 音频源 | 安卓 | ios | 网络 | macos |
|---|---|---|---|---|
| ?资产文件(资产路径) | ✅ | ✅ | ✅ | ✅ |
| 网络文件(URL) | ✅ | ✅ | ✅ | ✅ |
| ?本地文件(路径) | ✅ | ✅ | ✅ | ✅ |
| ?网络直播 /无线电(URL) (默认,hls,dash,smoothstream ) | ✅ | ✅ | ✅ | ✅ |
| 特征 | 安卓 | ios | 网络 | macos |
|---|---|---|---|---|
| ?多个玩家 | ✅ | ✅ | ✅ | ✅ |
| ?打开播放列表 | ✅ | ✅ | ✅ | ✅ |
| 系统通知 | ✅ | ✅ | ||
| 蓝牙动作 | ✅ | ✅ | ||
| ?尊重系统静音模式 | ✅ | ✅ | ||
| ?暂停电话 | ✅ | ✅ |
| 命令 | 安卓 | ios | 网络 | macos |
|---|---|---|---|---|
| ▶玩 | ✅ | ✅ | ✅ | ✅ |
| ⏸暂停 | ✅ | ✅ | ✅ | ✅ |
| ⏹停下来 | ✅ | ✅ | ✅ | ✅ |
| ⏩寻求(位置) | ✅ | ✅ | ✅ | ✅ |
| ⏪⏩Seekby(位置) | ✅ | ✅ | ✅ | ✅ |
| ⏩前进(速度) | ✅ | ✅ | ✅ | ✅ |
| ⏪倒带(速度) | ✅ | ✅ | ✅ | ✅ |
| ⏭下一个 | ✅ | ✅ | ✅ | ✅ |
| ⏮上一个 | ✅ | ✅ | ✅ | ✅ |
| 小部件 | 安卓 | ios | 网络 | macos |
|---|---|---|---|---|
| ?音频小部件 | ✅ | ✅ | ✅ | ✅ |
| ?小部件构建者 | ✅ | ✅ | ✅ | ✅ |
| ? AudioPlayer构建器扩展 | ✅ | ✅ | ✅ | ✅ |
| 特性 | 安卓 | ios | 网络 | macos |
|---|---|---|---|---|
| ?环形 | ✅ | ✅ | ✅ | ✅ |
| ?洗牌 | ✅ | ✅ | ✅ | ✅ |
| ?获取/设置音量 | ✅ | ✅ | ✅ | ✅ |
| ⏩获取/设置播放速度 | ✅ | ✅ | ✅ | ✅ |
| ⏩获取/设置俯仰 | ✅ |
| 听众 | 安卓 | ios | 网络 | macos |
|---|---|---|---|---|
| ?听众准备就绪(已完成) | ✅ | ✅ | ✅ | ✅ |
| ?侦听器电流位置 | ✅ | ✅ | ✅ | ✅ |
| ?听众完成了 | ✅ | ✅ | ✅ | ✅ |
| ?听众缓冲 | ✅ | ✅ | ✅ | ✅ |
| ?听众音量 | ✅ | ✅ | ✅ | ✅ |
| 听众玩速度 | ✅ | ✅ | ✅ | ✅ |
| 听众音调 | ✅ |
无需使用Assets_audio_player将歌曲复制到媒体缓存,您可以直接从资产中打开它们。
flutter :
assets :
- assets/audios/ final assetsAudioPlayer = AssetsAudioPlayer ();
assetsAudioPlayer. open (
Audio ( "assets/audios/song1.mp3" ),
);您也可以从URL播放网络歌曲
final assetsAudioPlayer = AssetsAudioPlayer ();
try {
await assetsAudioPlayer. open (
Audio . network ( "http://www.mysite.com/myMp3file.mp3" ),
);
} catch (t) {
//mp3 unreachable
}URL的直播 /收音机
与网络的主要区别,如果您暂停/播放,在直播上,它将恢复以介绍持续时间
final assetsAudioPlayer = AssetsAudioPlayer ();
try {
await assetsAudioPlayer. open (
Audio . liveStream ( MY_LIVESTREAM_URL ),
);
} catch (t) {
//stream unreachable
}并播放文件中的歌曲
//create a new player
final assetsAudioPlayer = AssetsAudioPlayer ();
assetsAudioPlayer. open (
Audio . file ( FILE_URI ),
);对于文件URI,请查看https://pub.dev/packages/path_provider
assetsAudioPlayer. playOrPause ();
assetsAudioPlayer. play ();
assetsAudioPlayer. pause ();assetsAudioPlayer. seek ( Duration to);
assetsAudioPlayer. seekBy ( Duration by);assetsAudioPlayer. forwardRewind ( double speed);
//if positive, forward, if negative, rewind assetsAudioPlayer. stop ();

在iOS上,它将使用MPNowPlayingInfoCenter
final audio = Audio . network ( "/assets/audio/country.mp3" ,
metas : Metas (
title : "Country" ,
artist : "Florent Champigny" ,
album : "CountryAlbum" ,
image : MetasImage . asset ( "assets/images/country.jpg" ), //can be MetasImage.network
),
);showNotification: true _player. open (audio, showNotification : true )自定义图标(仅Android)
确保您在android/res/drawable中添加了这些图标!!!不在扑朔迷离的资产上!!!!
await _assetsAudioPlayer. open (
myAudio,
showNotification : true ,
notificationSettings : NotificationSettings (
customStopIcon : AndroidResDrawable (name : "ic_stop_custom" ),
customPauseIcon : AndroidResDrawable (name : "ic_pause_custom" ),
customPlayIcon : AndroidResDrawable (name : "ic_play_custom" ),
customPrevIcon : AndroidResDrawable (name : "ic_prev_custom" ),
customNextIcon : AndroidResDrawable (name : "ic_next_custom" ),
)
而且不要忘记告诉Proguard将这些资源保留为发布模式
(零件保留资源)
https://sites.google.com/a/android.com/tools/tech-docs/new-build-system/resource-shrinking
<? xml version = " 1.0 " encoding = " utf-8 " ?>
< resources xmlns : tools = " http://schemas.android.com/tools "
tools:keep= " @drawable/ic_next_custom, @drawable/ic_prev_custom, @drawable/ic_pause_custom, @drawable/ic_play_custom, @drawable/ic_stop_custom " />将图标添加到Android的res文件夹中(Android/App/SRC/Main/Res)
将此图标引用到您的AndroidManifest(Android/app/src/main/androidManifest.xml)中
< meta-data
android : name = " assets.audio.player.notification.icon "
android : resource = " @drawable/ic_music_custom " />您还可以更改动作图标
<meta-data
android:name="assets.audio.player.notification.icon.play"
android:resource="@drawable/ic_play_custom"/>
<meta-data
android:name="assets.audio.player.notification.icon.pause"
android:resource="@drawable/ic_pause_custom"/>
<meta-data
android:name="assets.audio.player.notification.icon.stop"
android:resource="@drawable/ic_stop_custom"/>
<meta-data
android:name="assets.audio.player.notification.icon.next"
android:resource="@drawable/ic_next_custom"/>
<meta-data
android:name="assets.audio.player.notification.icon.prev"
android:resource="@drawable/ic_prev_custom"/>
添加主要
AssetsAudioPlayer . setupNotificationsOpenAction ((notification) {
//custom action
return true ; //true : handled, does not notify others listeners
//false : enable others listeners to handle it
});然后,如果您想在小部件上进行自定义操作
AssetsAudioPlayer . addNotificationOpenAction ((notification) {
//custom action
return false ; //true : handled, does not notify others listeners
//false : enable others listeners to handle it
});您可以启用/禁用通知操作
open ( AUDIO ,
showNotification : true ,
notificationSettings : NotificationSettings (
prevEnabled : false , //disable the previous button
//and have a custom next action (will disable the default action)
customNextAction : (player) {
print ( "next" );
}
)
)创建音频后,只需致电
audio. updateMetas (
player : _assetsAudioPlayer, //add the player if the audio is actually played
title : "My new title" ,
artist : "My new artist" ,
//if I not provide a new album, it keep the old one
image : MetasImage . network (
//my new image url
),
);您必须启用通知才能使它们工作
可用远程命令:
(目前仅适用于Android)
在打开歌曲/播放列表时,添加策略
assetsAudioPlayer. open (
...
headPhoneStrategy : HeadPhoneStrategy .pauseOnUnplug,
//headPhoneStrategy: HeadPhoneStrategy.none, //default
//headPhoneStrategy: HeadPhoneStrategy.pauseOnUnplugPlayOnPlug,
)如果您也想在蓝牙上使用它,则必须在AndroidManifest.xml中添加蓝牙许可
< uses-permission android : name = " android.permission.BLUETOOTH " />您可以使用Assetsaudioplayer.newplayer()创建新的Assetsaudioplayer,它将在其他本机媒体播放器中播放歌曲
这将使可以同时播放两首歌
您可以拥有任意数量的球员!
///play 3 songs in parallel
AssetsAudioPlayer . newPlayer (). open (
Audio ( "assets/audios/song1.mp3" )
);
AssetsAudioPlayer . newPlayer (). open (
Audio ( "assets/audios/song2.mp3" )
);
//another way, with create, open, play & dispose the player on finish
AssetsAudioPlayer . playAndForget (
Audio ( "assets/audios/song3.mp3" )
);每个玩家都有一个唯一生成的id ,您可以使用
final player = AssetsAudioPlayer . withId (id : "MY_UNIQUE_ID" );assetsAudioPlayer. open (
Playlist (
audios : [
Audio ( "assets/audios/song1.mp3" ),
Audio ( "assets/audios/song2.mp3" )
]
),
loopMode : LoopMode .playlist //loop the full playlist
);
assetsAudioPlayer. next ();
assetsAudioPlayer. prev ();
assetsAudioPlayer. playlistPlayAtIndex ( 1 );如果您想要一种更加颤抖的方式播放音频,请尝试AudioWidget !

//inside a stateful widget
bool _play = false ;
@override
Widget build ( BuildContext context) {
return AudioWidget . assets (
path : "assets/audios/country.mp3" ,
play : _play,
child : RaisedButton (
child : Text (
_play ? "pause" : "play" ,
),
onPressed : () {
setState (() {
_play = ! _play;
});
}
),
onReadyToPlay : (duration) {
//onReadyToPlay
},
onPositionChanged : (current, duration) {
//onPositionChanged
},
);
}怎么办?停止 ? AudioWidget?
只需从树上删除音频!或只是继续play: false
所有听众都使用RXDART曝光流,Assetsaudioplayer将某些侦听器视为ValueObserbable(可观察到可同步访问最后发射项目的可观察);
//The current playing audio, filled with the total song duration
assetsAudioPlayer.current //ValueObservable<PlayingAudio>
//Retrieve directly the current played asset
final PlayingAudio playing = assetsAudioPlayer.current.value;
//Listen to the current playing song
assetsAudioPlayer.current. listen ((playingAudio){
final asset = playingAudio.assetAudio;
final songDuration = playingAudio.duration;
}) //Listen to the current playing song
final duration = assetsAudioPlayer.current.value.duration;assetsAudioPlayer.currentPosition //ValueObservable<Duration>
//retrieve directly the current song position
final Duration position = assetsAudioPlayer.currentPosition.value;
return StreamBuilder (
stream : assetsAudioPlayer.currentPosition,
builder : (context, asyncSnapshot) {
final Duration duration = asyncSnapshot.data;
return Text (duration. toString ());
}),或使用玩家构建器!
PlayerBuilder . currentPosition (
player : _assetsAudioPlayer,
builder : (context, duration) {
return Text (duration. toString ());
}
)或玩家建造者扩展
_assetsAudioPlayer. builderCurrentPosition (
builder : (context, duration) {
return Text (duration. toString ());
}
)布尔可观察的代表当前的媒体演奏者的状态
assetsAudioPlayer.isPlaying // ValueObservable<bool>
//retrieve directly the current player state
final bool playing = assetsAudioPlayer.isPlaying.value;
//will follow the AssetsAudioPlayer playing state
return StreamBuilder (
stream : assetsAudioPlayer.isPlaying,
builder : (context, asyncSnapshot) {
final bool isPlaying = asyncSnapshot.data;
return Text (isPlaying ? "Pause" : "Play" );
}),或使用玩家构建器!
PlayerBuilder . isPlaying (
player : _assetsAudioPlayer,
builder : (context, isPlaying) {
return Text (isPlaying ? "Pause" : "Play" );
}
)或玩家建造者扩展
_assetsAudioPlayer. builderIsPlaying (
builder : (context, isPlaying) {
return Text (isPlaying ? "Pause" : "Play" );
}
)更改音量(0.0和1.0之间)
assetsAudioPlayer. setVolume ( 0.5 );媒体播放器可以遵循系统的“音量模式”(振动,静音,正常),只需将respectSilentMode选择参数设置为true
_player. open ( PLAYABLE , respectSilentMode : true );https://developer.android.com/reference/android/media/audiomanager.html?hl=fr#getringermode()
https://developer.apple.com/documentation/avfoundation/avaudiosessioncategorysoloambient
听音量
return StreamBuilder (
stream : assetsAudioPlayer.volume,
builder : (context, asyncSnapshot) {
final double volume = asyncSnapshot.data;
return Text ( "volume : $ volume " );
}),或使用玩家构建器!
PlayerBuilder . volume (
player : _assetsAudioPlayer,
builder : (context, volume) {
return Text ( "volume : $ volume " );
}
)当当前歌曲结束时打电话给
它给出了刚完成的播放音频
assetsAudioPlayer.playlistAudioFinished //ValueObservable<Playing>
assetsAudioPlayer.playlistAudioFinished. listen (( Playing playing){
})当完整的播放列表完成播放时打电话
assetsAudioPlayer.playlistFinished //ValueObservable<bool>
assetsAudioPlayer.playlistFinished. listen ((finished){
}) final LoopMode loopMode = assetsAudioPlayer.loop;
// possible values
// LoopMode.none : not looping
// LoopMode.single : looping a single audio
// LoopMode.playlist : looping the fyll playlist
assetsAudioPlayer. setLoopMode ( LoopMode .single);
assetsAudioPlayer.loopMode. listen ((loopMode){
//listen to loop
})
assetsAudioPlayer. toggleLoop (); //toggle the value of loopingassetsAudioPlayer. setPlaySpeed ( 1.5 );
assetsAudioPlayer.playSpeed. listen ((playSpeed){
//listen to playSpeed
})
//change play speed for a particular Audio
Audio audio = Audio . network (
url,
playSpeed : 1.5
);
assetsAudioPlayer. open (audio);assetsAudioPlayer. setPitch ( 1.2 );
assetsAudioPlayer.pitch. listen ((pitch){
//listen to pitch
})
//change pitch for a particular Audio
Audio audio = Audio . network (
url,
pitch : 1.2
);
assetsAudioPlayer. open (audio);默认情况下,在播放错误时,它会停止音频
但是您可以添加自定义行为
_player.onErrorDo = (handler){
handler.player. stop ();
};打开另一个音频
_player.onErrorDo = (handler){
handler.player. open ( ANOTHER_AUDIO );
};尝试在同一位置再次打开
_player.onErrorDo = (handler){
handler.player. open (
handler.playlist. copyWith (
startIndex : handler.playlistIndex
),
seek : handler.currentPosition
);
}; Android usesCleartextTraffic="true"允许HTTPS调用,如果您使用HTTP,您将出现错误
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:usesCleartextTraffic="true"
...>
...
</application>
</manifest>
iOS仅允许HTTPS调用NSAppTransportSecurity如果您使用HTTP,您NSAllowsArbitraryLoads出现错误
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
要启用MACOS上的HTTP调用,您必须将输入/输出调用功能添加到info.plist中
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
<string>fetch</string>
</array>
<key>com.apple.security.network.client</key>
<true/>
在你的
Runner/DebugProfile.entitlements
添加
<key>com.apple.security.network.client</key>
<true/>
完整的Runner/DebugProfile.entitlements
<?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>
样品中使用的所有uses都来自https://www.freemusicarchive.org/