Reproduce música / audio almacenado en archivos de activos (simultáneamente) directamente desde Flutter (Android / iOS / Web / MacOS).
También puede usar archivos de audio reproducir desde la red utilizando su URL, radios/livestress y archivos locales
La notificación se puede mostrar en Android e iOS, y se manejan las acciones de Bluetooth
flutter :
assets :
- assets/audios/ AssetsAudioPlayer . newPlayer (). open (
Audio ( "assets/audios/song1.mp3" ),
autoStart : true ,
showNotification : true ,
);

dependencies :
assets_audio_player : ^3.0.8 Funciona con flutter: ">=3.3.0" , asegúrese de actualizar su SDK
¿Te gusta el paquete? Cómprame un kofi :)
| Fuente de audio | Androide | iOS | Web | Macosa |
|---|---|---|---|---|
| ? ️ Archivo de activos (ruta de activo) | ✅ | ✅ | ✅ | ✅ |
| Archivo de red (URL) | ✅ | ✅ | ✅ | ✅ |
| ? Archivo local (ruta) | ✅ | ✅ | ✅ | ✅ |
| ? Red en vivo / radio (URL) ( Predeterminado, HLS, Dash, SmoothStream ) | ✅ | ✅ | ✅ | ✅ |
| Característica | Androide | iOS | Web | Macosa |
|---|---|---|---|---|
| ? Múltiples jugadores | ✅ | ✅ | ✅ | ✅ |
| ? Lista de reproducción abierta | ✅ | ✅ | ✅ | ✅ |
| Notificación del sistema | ✅ | ✅ | ||
| Acciones Bluetooth | ✅ | ✅ | ||
| ? Respetar el modo silencioso del sistema | ✅ | ✅ | ||
| ? Pausa en la llamada telefónica | ✅ | ✅ |
| Comandos | Androide | iOS | Web | Macosa |
|---|---|---|---|---|
| ▶ Jugar | ✅ | ✅ | ✅ | ✅ |
| ⏸ Pausa | ✅ | ✅ | ✅ | ✅ |
| ⏹ Detente | ✅ | ✅ | ✅ | ✅ |
| ⏩ buscar (posición) | ✅ | ✅ | ✅ | ✅ |
| ⏪⏩ Seekby (posición) | ✅ | ✅ | ✅ | ✅ |
| ⏩ Forward (velocidad) | ✅ | ✅ | ✅ | ✅ |
| ⏪ Rewind (velocidad) | ✅ | ✅ | ✅ | ✅ |
| ⏭ Siguiente | ✅ | ✅ | ✅ | ✅ |
| ⏮ Anterior | ✅ | ✅ | ✅ | ✅ |
| Widgets | Androide | iOS | Web | Macosa |
|---|---|---|---|---|
| ? Widget de audio | ✅ | ✅ | ✅ | ✅ |
| ? Constructores de widgets | ✅ | ✅ | ✅ | ✅ |
| ? Extensión de constructores de audioplayer | ✅ | ✅ | ✅ | ✅ |
| Propiedades | Androide | iOS | Web | Macosa |
|---|---|---|---|---|
| ? Bucle | ✅ | ✅ | ✅ | ✅ |
| ? Barajar | ✅ | ✅ | ✅ | ✅ |
| ? Get/Set Volume | ✅ | ✅ | ✅ | ✅ |
| ⏩ Obtener/establecer la velocidad de juego | ✅ | ✅ | ✅ | ✅ |
| ⏩ Obtener/establecer | ✅ |
| Oyentes | Androide | iOS | Web | Macosa |
|---|---|---|---|---|
| ? Oyente On Ready (Completyural) | ✅ | ✅ | ✅ | ✅ |
| ? Pososición actual del oyente | ✅ | ✅ | ✅ | ✅ |
| ? Oyente terminado | ✅ | ✅ | ✅ | ✅ |
| ? Búfer de oyentes | ✅ | ✅ | ✅ | ✅ |
| ? Volumen del oyente | ✅ | ✅ | ✅ | ✅ |
| ? Velocidad de juego del oyente | ✅ | ✅ | ✅ | ✅ |
| ? Tablero del oyente | ✅ |
No es necesario copiar canciones a un caché de medios, con activos_audio_player puede abrirlas directamente desde los activos.
flutter :
assets :
- assets/audios/ final assetsAudioPlayer = AssetsAudioPlayer ();
assetsAudioPlayer. open (
Audio ( "assets/audios/song1.mp3" ),
);También puedes reproducir canciones de red de URL
final assetsAudioPlayer = AssetsAudioPlayer ();
try {
await assetsAudioPlayer. open (
Audio . network ( "http://www.mysite.com/myMp3file.mp3" ),
);
} catch (t) {
//mp3 unreachable
}Transmisión en vivo / radio de URL
La principal diferencia con la red, si se detiene/juega, en la transmisión en vivo se reanudará a la duración actual
final assetsAudioPlayer = AssetsAudioPlayer ();
try {
await assetsAudioPlayer. open (
Audio . liveStream ( MY_LIVESTREAM_URL ),
);
} catch (t) {
//stream unreachable
}Y reproducir canciones del archivo
//create a new player
final assetsAudioPlayer = AssetsAudioPlayer ();
assetsAudioPlayer. open (
Audio . file ( FILE_URI ),
);Para el URI de archivo, mire 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 ();

En iOS, usará 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 )Icono personalizado (solo Android)
¡Asegúrese de agregar esos iconos dentro de su 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" ),
)
Y no olvide decirle a Proguard que mantenga esos recursos para el modo de liberación
(Parte manteniendo los recursos)
https://sites.google.com/a/android.com/tools/tech-docs/new-build-system/resource-shinking
<? 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 " /> Agregue su icono a la carpeta res de su Android (Android/App/Src/Main/Res)
Referencia a este icono en su AndroidManifest (Android/App/Src/Main/AndroidManifest.xml)
< meta-data
android : name = " assets.audio.player.notification.icon "
android : resource = " @drawable/ic_music_custom " />También puedes cambiar los iconos de acciones
<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"/>
Agregar en
AssetsAudioPlayer . setupNotificationsOpenAction ((notification) {
//custom action
return true ; //true : handled, does not notify others listeners
//false : enable others listeners to handle it
});Entonces, si quieres una acción personalizada en widget
AssetsAudioPlayer . addNotificationOpenAction ((notification) {
//custom action
return false ; //true : handled, does not notify others listeners
//false : enable others listeners to handle it
});Puede habilitar/deshabilitar una acción de notificación
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" );
}
)
)Después de su creación de audio, solo llame
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
),
);Tienes que habilitar la notificación para que funcionen
Comandos remotos disponibles:
(Solo para Android por ahora)
Mientras abre una canción/lista de reproducción, agregue una estrategia
assetsAudioPlayer. open (
...
headPhoneStrategy : HeadPhoneStrategy .pauseOnUnplug,
//headPhoneStrategy: HeadPhoneStrategy.none, //default
//headPhoneStrategy: HeadPhoneStrategy.pauseOnUnplugPlayOnPlug,
)Si también desea que funcione en Bluetooth, tendrá que agregar el permiso de Bluetooth dentro de su AndroidManifest.xml
< uses-permission android : name = " android.permission.BLUETOOTH " />Puede crear un nuevo AssetSaudioPlayer usando AssetSaudioPlayer.NewPlayer (), que reproducirá canciones en un reproductor multimedia nativo diferente
Esto permitirá reproducir dos canciones simultáneamente
¡Puedes tener tantos jugadores como quieras!
///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" )
); Cada jugador tiene una id generada única, puede recuperarlos o crearlos manualmente usando
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 ); Si quieres una forma más de aleteo de reproducir audio, ¡prueba el 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
},
);
}¿Cómo? detener ? el AudioWidget?
¡Simplemente retire el audio del árbol! O simplemente mantener play: false
Todos los oyentes exponen transmisiones con RXDART, AssetSaudioPlayer expone a algunos oyentes como ValueBServable (observable que proporciona acceso sincrónico al último elemento emitido);
//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 ());
}),¡O use un PlayerBuilder!
PlayerBuilder . currentPosition (
player : _assetsAudioPlayer,
builder : (context, duration) {
return Text (duration. toString ());
}
)o extensión de constructor de jugadores
_assetsAudioPlayer. builderCurrentPosition (
builder : (context, duration) {
return Text (duration. toString ());
}
)Observable booleano que representa el estado actual de reproducción de medias
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" );
}),¡O use un PlayerBuilder!
PlayerBuilder . isPlaying (
player : _assetsAudioPlayer,
builder : (context, isPlaying) {
return Text (isPlaying ? "Pause" : "Play" );
}
)o extensión de constructor de jugadores
_assetsAudioPlayer. builderIsPlaying (
builder : (context, isPlaying) {
return Text (isPlaying ? "Pause" : "Play" );
}
)Cambiar el volumen (entre 0.0 y 1.0)
assetsAudioPlayer. setVolume ( 0.5 ); El reproductor multimedia puede seguir el "modo de volumen" del sistema (vibrar, apagar, normal) simplemente establecer el parámetro opcional de respectSilentMode como true
_player. open ( PLAYABLE , respectSilentMode : true );https://developer.android.com/reference/android/media/audiomomanerer.html?hl=fr#getringermode ()
https://developer.apple.com/documentation/avfoundation/avaudiosessioncategorysoloambient
Escucha el volumen
return StreamBuilder (
stream : assetsAudioPlayer.volume,
builder : (context, asyncSnapshot) {
final double volume = asyncSnapshot.data;
return Text ( "volume : $ volume " );
}),¡O use un PlayerBuilder!
PlayerBuilder . volume (
player : _assetsAudioPlayer,
builder : (context, volume) {
return Text ( "volume : $ volume " );
}
)Llamado cuando la canción actual ha terminado para tocar,
da el audio de reproducción que acaba de terminar
assetsAudioPlayer.playlistAudioFinished //ValueObservable<Playing>
assetsAudioPlayer.playlistAudioFinished. listen (( Playing playing){
})Llamado cuando la lista de reproducción completa ha terminado para jugar
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);Por defecto, al reproducir el error, detiene el audio
Pero puede agregar un comportamiento personalizado
_player.onErrorDo = (handler){
handler.player. stop ();
};Abrir otro audio
_player.onErrorDo = (handler){
handler.player. open ( ANOTHER_AUDIO );
};Intenta abrir de nuevo en la misma posición
_player.onErrorDo = (handler){
handler.player. open (
handler.playlist. copyWith (
startIndex : handler.playlistIndex
),
seek : handler.currentPosition
);
}; Android solo permite las llamadas HTTPS, tendrá un error si está utilizando http, no olvide agregar permiso de Internet y SEET usesCleartextTraffic="true" en su androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:usesCleartextTraffic="true"
...>
...
</application>
</manifest>
iOS solo permite NSAllowsArbitraryLoads llamadas HTTPS, tendrá un error si está utilizando http, no olvide editar su información NSAppTransportSecurity
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Para habilitar las llamadas HTTP en MacOS, debe agregar capacidades de llamadas de entrada/salida en 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/>
Y en tu
Runner/DebugProfile.entitlements
agregar
<key>com.apple.security.network.client</key>
<true/>
Complete 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>
Todas las músicas utilizadas en las muestras vinieron de https://www.freemusicarchive.org/