audioplayers 0.15.1

  • Readme
  • Changelog
  • Example
  • Installing
  • 99

AudioPlayers #

Build Status

A Flutter plugin to play multiple simultaneously audio files, works for Android, iOS, macOS and web (WIP).

Install #

This was orginally forked from rxlabz's audioplayer, but the name was changed to audioplayers (mind the 's'); so, to add the dependency:

  audioplayers: ^0.15.1

Discord channel #

We have created a channel for audioplayers help on Fireslime's discord, join it here

Support us #

You can support us by becoming a patron on Patreon, any support is much appreciated.


Troubleshooting #

Before opening an issue, please refer to the troubleshoot guide

Usage #

An AudioPlayer instance can play a single audio at a time. To create it, simply call the constructor:

    AudioPlayer audioPlayer = AudioPlayer();

To use the low latency API, better for gaming sounds, use:

    AudioPlayer audioPlayer = AudioPlayer(mode: PlayerMode.LOW_LATENCY);

In this mode the backend won't fire any duration or position updates. Also, it is not possible to use the seek method to set the audio a specific position. This mode is also not available on web.

You can create multiple instances to play audio simultaneously.

For all methods that return a Future<int>: that's the status of the operation. If 1, the operation was successful. Otherwise it's the platform native error code.

Logs are disable by default! To debug, run:

  AudioPlayer.logEnabled = true;

Playing Audio #

There are three possible sources of audio:

  • Remote file on the Internet
  • Local file on the user's device
  • Local asset from your Flutter project

Both for Remote Files or Local Files, use the play method, just setting appropriately the flag isLocal.

For Local Assets, you have to use the AudioCache class (see below).

To play a Remote File, just call play with the url (the isLocal parameter is false by default):

If you want to play audio for a long period of time, you need to set appropriately the flag stayAwake, If you pass setAwake as true you need to add this permission to your app manifest: <uses-permission android:name="android.permission.WAKE_LOCK" />.

  play() async {
    int result = await;
    if (result == 1) {
      // success

For a Local File, add the isLocal parameter:

  playLocal() async {
    int result = await, isLocal: true);

The isLocal flag is required only because iOS and macOS make a difference about it (Android doesn't care either way).

There is also an optional named double volume parameter, that defaults to 1.0. It can go from 0.0 (mute) to 1.0 (max), varying linearly.

The volume can also be changed at any time using the setVolume method.

Controlling #

Note: these features are not implemented in web yet.

After playing, you can control the audio with pause, stop and seek commands.

Pause will pause the audio but keep the cursor where it was. Subsequently calling play will resume from this point.

  int result = await audioPlayer.pause();

Stop will stop the audio and reset the cursor. Subsequently calling play will resume from the beginning.

  int result = await audioPlayer.stop();

Finally, use seek to jump through your audio:

  int result = await 1200));

Also, you can resume (like play, but without new parameters):

  int result = await audioPlayer.resume();

Finer Control #

By default, the player will be release once the playback is finished or the stop method is called.

This is because on Android, a MediaPlayer instance can be quite resource-heavy, and keep it unreleased would cause performance issues if you play lots of different audios.

On iOS and macOS this doesn't apply, so release does nothing.

You can change the Release Mode to determine the actual behavior of the MediaPlayer once finished/stopped. There are three options:

  • RELEASE: default mode, will release after stop/completed.
  • STOP: will never release; calling play should be faster.
  • LOOP: will never release; after completed, it will start playing again on loop.

If you are not on RELEASE mode, you should call the release method yourself; for example:

  await audioPlayer.setUrl('clicking.mp3'); // prepare the player with this audio but do not start playing
  await audioPlayer.setReleaseMode(ReleaseMode.STOP); // set release mode so that it never releases

  // on button click
  await audioPlayer.resume(); // quickly plays the sound, will not release

  // on exiting screen
  await audioPlayer.release(); // manually release when no longer needed

Despite the complex state diagram of Android's MediaPlayer, an AudioPlayer instance should never have an invalid state. Even if it's released, if resume is called, the data will be fetch again.

Stream routing

You can choose between speakers and earpiece. By default using speakers. Toggle between speakers and earpiece.

int result = await player.earpieceOrSpeakersToggle();

⚠️ iOS stream routing not implemented

Streams #

Note: streams are not available on web yet.

The AudioPlayer supports subscribing to events like so:

Duration Event

This event returns the duration of the file, when it's available (it might take a while because it's being downloaded or buffered).

  player.onDurationChanged.listen((Duration d) {
    print('Max duration: $d');
    setState(() => duration = d);

Position Event

This Event updates the current position of the audio. You can use it to make a progress bar, for instance.

  player.onAudioPositionChanged.listen((Duration  p) => {
    print('Current position: $p');
    setState(() => position = p);

State Event

This Event returns the current player state. You can use it to show if player playing, or stopped, or paused.

  player.onPlayerStateChanged.listen((AudioPlayerState s) => {
    print('Current player state: $s');
    setState(() => playerState = s);

Completion Event

This Event is called when the audio finishes playing; it's used in the loop method, for instance.

It does not fire when you interrupt the audio with pause or stop.

  player.onPlayerCompletion.listen((event) {
    setState(() {
      position = duration;

Error Event

This is called when an unexpected error is thrown in the native code.

  player.onPlayerError.listen((msg) {
    print('audioPlayer error : $msg');
    setState(() {
      playerState = PlayerState.stopped;
      duration = Duration(seconds: 0);
      position = Duration(seconds: 0);

AudioCache #

In order to play Local Assets, you must use the AudioCache class.

Flutter does not provide an easy way to play audio on your assets, but this class helps a lot. It actually copies the asset to a temporary folder in the device, where it is then played as a Local File.

It works as a cache because it keeps track of the copied files so that you can replay them without delay.

You can find the full documentation for this class here.

playerId #

By default, each time you initialize a new instance of AudioPlayer a unique playerId is generated and assigned using uuid package, this is designed this way to play multiple audio files simultaneously, if you want to play using the same instance that was created before simply pass your playerId when creating a new AudioPlayer instance.

final audioPlayer = AudioPlayer(playerId: 'my_unique_playerId');

Supported Formats #

You can check a list of supported formats below:

⚠️ iOS & macOS App Transport Security #

By default iOS and macOS forbid loading from non-https url. To cancel this restriction on iOS or macOS you must edit your .plist and add:


⚠️ macOS Outgoing Connections #

By default, Flutter macOS apps don't allow outgoing connections, so playing audio files/streams from the internet won't work. To fix this, add the following to the .entitlements files for your app:


Note: On Android by default, there is a restriction not allowing traffic from HTTP resources. There is a fix for this and it requires adding android:usesCleartextTraffic="true" within your AndroidManifest.xml file located in android/app/src/main/AndroidManifest.xml.

Here is an example of how it should look like:

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />

Credits #

This was originally a fork of rxlabz's audioplayer, but since we have diverged and added more features.

Thanks for @rxlabz for the amazing work!

Changelog #

[next] #

audioplayers 0.15.1 #

  • Fix web for release mode

audioplayers 0.15.0 #

  • Improve loop/readme for web support
  • Audio cache support for web
  • Re-adding partial web support

audioplayers 0.14.2 #

  • Fix pubspec problem because of web file

audioplayers 0.14.1 #

  • Adding linter, tests and flutter_driver integration tests to a CI (github actions)
  • Minor fixes to the APIs and documentation
  • Fix restarting the playback of a failed AVPlayerItem
  • Prevent exceptions when null values are passed to notifications center
  • Prevent crash by checking if headlessServiceInitialized before invoking onNotificationBackgroundPlayerStateChanged

audioplayers 0.14.0 #

  • Adding macOs support
  • ios:fix lack of seek completion handle
  • ios Delay start fixed

audioplayers 0.13.7 #

  • Bump dependencies, improve gitignore
  • Upgrade pubspec pattern

audioplayers 0.13.6 #

  • added setPlaybackRate feature for Android
  • Automatic detect address is local or remote (thanks, @saeed-golshan)

audioplayers 0.13.5 #

  • fixed crash on iOS when startHeadlessService() wasn't called on AudioPlayer (by @JesseScott)

audioplayers 0.13.4 #

  • fixing missing cleanup on hot restart on Android
  • Background notification updates on iOS

audioplayers 0.13.3 #

  • audio notification area fixes
  • fix when other apps are playing sounds
  • fix android race condition
  • Support for registering plugin in background enviroment
  • fix typos and docs

audioplayers 0.13.2 #

  • Handling plugin dealloc and onTimeInterval crashs (thanks @chedechao111)
  • Audio position update when the audio is paused (thanks @bjornjacobs)

audioplayers 0.13.1 #

  • Added stayAwake feature (thanks, @danielR2001)
  • Improved dispose method (thanks, @hugocbpassos)
  • Added getCurrentPosition (thanks, @hariom08)
  • Some bug fixes and small changes

audioplayers 0.13.0 #

  • Call onDurationChanged after setUrl() to be consistent with ios version (thanks @subhash279)
  • Adding getDuration feature iOS/Android (thanks @alecorsino)

audioplayers 0.12.1 #

  • Fixes bug where the stream handlers were not called due to exception on the handler
  • Proper error message when errors in the dart handler occurs

audioplayers 0.12.0 #

  • Update to path_provider 1.1.0
  • Upgrade to Swift 5 in example project setting (thanks @jerryzhoujw)

audioplayers 0.11.0 #

  • Breaking change. Migrate from the deprecated original Android Support Library to AndroidX. This shouldn't result in any functional changes, but it requires any Android apps using this plugin to also migrate if they're using the original support library.

audioplayers 0.10.1 #

  • Seek and play now works with milliseconds instead of second (thanks, @catoldcui and @erickzanardo)

audioplayers 0.10.0 #

  • Added a low latency api for android (thanks, @feroult)

audioplayers 0.9.0 #

  • Improved callbacks using Streams to allow for multiple subscibers (thanks, @LucasCLuk)
  • Update uuid version to 2.0.0 (thanks, @BeMacized)

audioplayers 0.8.2 #

  • Update path_provider version (thanks, @apiraino)

audioplayers 0.8.1 #

  • Fix for duration when playing a stream
  • Added respectSilence flag in audioplayers, or isNotification for play methos in audio_cache False by default, to use player for local notification. Silent when device is in silent mode.

audioplayers 0.8.0 #

  • Allow setting seek position in play function (thanks @rob-patchett)
  • Get duration from the underlaying asset instead of from AVPlayerItem (thanks @andressade)
  • Adding player state (thanks @renancaraujo)
  • Set the audio session to active (thanks @benwicks)
  • Delay seek operations on Android until player is ready (thanks @jeffmikels)

audioplayers 0.7.8 #

  • Fix bug regarding name clash with other plugins (thanks @imtaehyun)

audioplayers 0.7.7 #

  • Fix bug when using nested files with audio cache (thanks @hotstu for reporting and @eclewlow for fixing)

audioplayers 0.7.6 #

  • Fix the nefarious bug of 'sound only playing through headphones' (thanks so much, @tsun424)

audioplayers 0.7.5 #

  • Fix SDK constraint for Dart 2.1 (thanks @snoofer and @sroddy)

audioplayers 0.7.4 #

  • Some more fixes to work without errors with Dart 2 stronger types

audioplayers 0.7.3 #

  • Support Android SDK 16-20 (thanks, @sroddy)
  • Avoid restarting a looping player if is stopped (thanks, @sroddy)

audioplayers 0.7.2 #

  • Bug fixes for iOS

audioplayers 0.7.1 #

  • Formatting

audioplayers 0.7.0 #

  • Improved lifecycle handling for android
  • Big performance boots
  • Allows for finer control of releasing (with setReleaseMode, setUrl, resume, release)
  • Allows for setting the volume at any time (with setVolume)
  • Added LOOP as a ReleaseMode options, making it significantly faster
  • Some other refactorings

audioplayers 0.6.0 #

  • Major Refactoring!
  • Renaming everything to audioplayers (mind the s)
  • Better logging
  • Added AudioCache (imported from Flame)
  • Adding tests!
  • Adding better example
  • Greatly improving README
  • Lots of other minor tweaks

audioplayers 0.5.2 #

  • don't call the onClomplete hook when you manually stop the audio

audioplayers 0.5.1 #

  • fix for dart 2 (thanks to @efortuna)

audioplayers 0.5.0 #

  • improves Android performance by not calling prepare on the main thread

audioplayers 0.4.1 #

  • fix seek for iOS

audioplayers 0.4.0 #

  • volume controls

audioplayers 0.3.0 #

  • working on iOS (thanks @feroult <3)

audioplayers 0.2.0 #

  • adding disable log option

audioplayers 0.1.0 #

  • support for multiple audios simultaneously

0.2.0 #

  • support for local files

0.1.0 #

0.0.2 #

Separated handlers for position, duration, completion and errors

  • setDurationHandler(TimeChangeHandler handler)

  • setPositionHandler(TimeChangeHandler handler)

  • setCompletionHandler(VoidCallback callback)

  • setErrorHandler(ErrorHandler handler)

  • new typedef

typedef void TimeChangeHandler(Duration duration);
typedef void ErrorHandler(String message);

0.0.1 #

  • first POC :
    • methods : play, pause, stop
    • a globalHandler for position, duration, completion and errors


import 'dart:async';
import 'dart:io';

import 'package:audioplayers/audio_cache.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
import 'package:flutter/src/foundation/constants.dart';

import 'player_widget.dart';

typedef void OnError(Exception exception);

const kUrl1 = '';
const kUrl2 = '';
const kUrl3 = '';

void main() {
  runApp(MaterialApp(home: ExampleApp()));

class ExampleApp extends StatefulWidget {
  _ExampleAppState createState() => _ExampleAppState();

class _ExampleAppState extends State<ExampleApp> {
  AudioCache audioCache = AudioCache();
  AudioPlayer advancedPlayer = AudioPlayer();
  String localFilePath;

  void initState() {

    if (kIsWeb) {
      // Calls to Platform.isIOS fails on web
    if (Platform.isIOS) {
      if (audioCache.fixedPlayer != null) {

  Future _loadFile() async {
    final bytes = await readBytes(kUrl1);
    final dir = await getApplicationDocumentsDirectory();
    final file = File('${dir.path}/audio.mp3');

    await file.writeAsBytes(bytes);
    if (await file.exists()) {
      setState(() {
        localFilePath = file.path;

  Widget remoteUrl() {
    return SingleChildScrollView(
      child: _Tab(children: [
          'Sample 1 ($kUrl1)',
          key: Key('url1'),
          style: TextStyle(fontWeight: FontWeight.bold),
        PlayerWidget(url: kUrl1),
          'Sample 2 ($kUrl2)',
          style: TextStyle(fontWeight: FontWeight.bold),
        PlayerWidget(url: kUrl2),
          'Sample 3 ($kUrl3)',
          style: TextStyle(fontWeight: FontWeight.bold),
        PlayerWidget(url: kUrl3),
          'Sample 4 (Low Latency mode) ($kUrl1)',
          style: TextStyle(fontWeight: FontWeight.bold),
        PlayerWidget(url: kUrl1, mode: PlayerMode.LOW_LATENCY),

  Widget localFile() {
    return _Tab(children: [
      Text('File: $kUrl1'),
      _Btn(txt: 'Download File to your Device', onPressed: () => _loadFile()),
      Text('Current local file path: $localFilePath'),
      localFilePath == null
          ? Container()
          : PlayerWidget(
              url: localFilePath,

  Widget localAsset() {
    return SingleChildScrollView(
      child: _Tab(children: [
        Text('Play Local Asset \'audio.mp3\':'),
        _Btn(txt: 'Play', onPressed: () =>'audio.mp3')),
        Text('Loop Local Asset \'audio.mp3\':'),
        _Btn(txt: 'Loop', onPressed: () => audioCache.loop('audio.mp3')),
        Text('Play Local Asset \'audio2.mp3\':'),
        _Btn(txt: 'Play', onPressed: () =>'audio2.mp3')),
        Text('Play Local Asset In Low Latency \'audio.mp3\':'),
            txt: 'Play',
            onPressed: () =>
      'audio.mp3', mode: PlayerMode.LOW_LATENCY)),
        Text('Play Local Asset Concurrently In Low Latency \'audio.mp3\':'),
            txt: 'Play',
            onPressed: () async {
              await'audio.mp3', mode: PlayerMode.LOW_LATENCY);
              await'audio2.mp3', mode: PlayerMode.LOW_LATENCY);
        Text('Play Local Asset In Low Latency \'audio2.mp3\':'),
            txt: 'Play',
            onPressed: () =>
      'audio2.mp3', mode: PlayerMode.LOW_LATENCY)),

  Future<int> _getDuration() async {
    File audiofile = await audioCache.load('audio2.mp3');
    await advancedPlayer.setUrl(
    int duration = await Future.delayed(
        Duration(seconds: 2), () => advancedPlayer.getDuration());
    return duration;

  getLocalFileDuration() {
    return FutureBuilder<int>(
      future: _getDuration(),
      builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
        switch (snapshot.connectionState) {
          case ConnectionState.none:
            return Text('No Connection...');
          case ConnectionState.waiting:
            return Text('Awaiting result...');
          case ConnectionState.done:
            if (snapshot.hasError) return Text('Error: ${snapshot.error}');
            return Text(
                'audio2.mp3 duration is: ${Duration(milliseconds:}');
        return null; // unreachable

  Widget notification() {
    return _Tab(children: [
      Text('Play notification sound: \'messenger.mp3\':'),
          txt: 'Play',
          onPressed: () =>
    'messenger.mp3', isNotification: true)),

  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
            initialData: Duration(),
            value: advancedPlayer.onAudioPositionChanged),
      child: DefaultTabController(
        length: 5,
        child: Scaffold(
          appBar: AppBar(
            bottom: TabBar(
              tabs: [
                Tab(text: 'Remote Url'),
                Tab(text: 'Local File'),
                Tab(text: 'Local Asset'),
                Tab(text: 'Notification'),
                Tab(text: 'Advanced'),
            title: Text('audioplayers Example'),
          body: TabBarView(
            children: [
                advancedPlayer: advancedPlayer,

class Advanced extends StatefulWidget {
  final AudioPlayer advancedPlayer;

  const Advanced({Key key, this.advancedPlayer}) : super(key: key);

  _AdvancedState createState() => _AdvancedState();

class _AdvancedState extends State<Advanced> {
  bool seekDone;

  void initState() {
    widget.advancedPlayer.seekCompleteHandler =
        (finished) => setState(() => seekDone = finished);

  Widget build(BuildContext context) {
    final audioPosition = Provider.of<Duration>(context);
    return SingleChildScrollView(
      child: _Tab(
        children: [
          Column(children: [
            Text('Source Url'),
            Row(children: [
                  txt: 'Audio 1',
                  onPressed: () => widget.advancedPlayer.setUrl(kUrl1)),
                  txt: 'Audio 2',
                  onPressed: () => widget.advancedPlayer.setUrl(kUrl2)),
                  txt: 'Stream',
                  onPressed: () => widget.advancedPlayer.setUrl(kUrl3)),
            ], mainAxisAlignment: MainAxisAlignment.spaceEvenly),
          Column(children: [
            Text('Release Mode'),
            Row(children: [
                  txt: 'STOP',
                  onPressed: () =>
                  txt: 'LOOP',
                  onPressed: () =>
                  txt: 'RELEASE',
                  onPressed: () => widget.advancedPlayer
            ], mainAxisAlignment: MainAxisAlignment.spaceEvenly),
          Column(children: [
            Row(children: [
                  txt: '0.0',
                  onPressed: () => widget.advancedPlayer.setVolume(0.0)),
                  txt: '0.5',
                  onPressed: () => widget.advancedPlayer.setVolume(0.5)),
                  txt: '1.0',
                  onPressed: () => widget.advancedPlayer.setVolume(1.0)),
                  txt: '2.0',
                  onPressed: () => widget.advancedPlayer.setVolume(2.0)),
            ], mainAxisAlignment: MainAxisAlignment.spaceEvenly),
          Column(children: [
            Row(children: [
                  txt: 'resume',
                  onPressed: () => widget.advancedPlayer.resume()),
                  txt: 'pause', onPressed: () => widget.advancedPlayer.pause()),
              _Btn(txt: 'stop', onPressed: () => widget.advancedPlayer.stop()),
                  txt: 'release',
                  onPressed: () => widget.advancedPlayer.release()),
            ], mainAxisAlignment: MainAxisAlignment.spaceEvenly),
          Column(children: [
            Text('Seek in milliseconds'),
            Row(children: [
                  txt: '100ms',
                  onPressed: () {
                        milliseconds: audioPosition.inMilliseconds + 100));
                    setState(() => seekDone = false);
                  txt: '500ms',
                  onPressed: () {
                        milliseconds: audioPosition.inMilliseconds + 500));
                    setState(() => seekDone = false);
                  txt: '1s',
                  onPressed: () {
                        .seek(Duration(seconds: audioPosition.inSeconds + 1));
                    setState(() => seekDone = false);
                  txt: '1.5s',
                  onPressed: () {
                        milliseconds: audioPosition.inMilliseconds + 1500));
                    setState(() => seekDone = false);
            ], mainAxisAlignment: MainAxisAlignment.spaceEvenly),
          Column(children: [
            Row(children: [
                  txt: '0.5',
                  onPressed: () =>
                      widget.advancedPlayer.setPlaybackRate(playbackRate: 0.5)),
                  txt: '1.0',
                  onPressed: () =>
                      widget.advancedPlayer.setPlaybackRate(playbackRate: 1.0)),
                  txt: '1.5',
                  onPressed: () =>
                      widget.advancedPlayer.setPlaybackRate(playbackRate: 1.5)),
                  txt: '2.0',
                  onPressed: () =>
                      widget.advancedPlayer.setPlaybackRate(playbackRate: 2.0)),
            ], mainAxisAlignment: MainAxisAlignment.spaceEvenly),
          Text('Audio Position: ${audioPosition}'),
          seekDone == null
              ? SizedBox(
                  width: 0,
                  height: 0,
              : Text(seekDone ? "Seek Done" : "Seeking..."),

class _Tab extends StatelessWidget {
  final List<Widget> children;

  const _Tab({Key key, this.children}) : super(key: key);

  Widget build(BuildContext context) {
    return Center(
      child: Container(
        alignment: Alignment.topCenter,
        padding: EdgeInsets.all(16.0),
        child: SingleChildScrollView(
          child: Column(
            children: children
                .map((w) => Container(child: w, padding: EdgeInsets.all(6.0)))

class _Btn extends StatelessWidget {
  final String txt;
  final VoidCallback onPressed;

  const _Btn({Key key, this.txt, this.onPressed}) : super(key: key);

  Widget build(BuildContext context) {
    return ButtonTheme(
        minWidth: 48.0,
        child: RaisedButton(child: Text(txt), onPressed: onPressed));

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:

  audioplayers: ^0.15.1

2. Install it

You can install packages from the command line:

with Flutter:

$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:

import 'package:audioplayers/audioplayers.dart';
Describes how popular the package is relative to other packages. [more]
Code health derived from static analysis. [more]
Reflects how tidy and up-to-date the package is. [more]
Weighted score of the above. [more]
Learn more about scoring.

We analyzed this package on May 24, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.1
  • pana: 0.13.8-dev
  • Flutter: 1.17.0


Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.6.0 <3.0.0
flutter 0.0.0
flutter_web_plugins 0.0.0
path_provider ^1.5.1 1.6.9
uuid ^2.0.4 2.0.4
Transitive dependencies
charcode 1.1.3
collection 1.14.12
convert 2.1.1
crypto 2.1.5
meta 1.1.8
path_provider_macos 0.0.4+3
path_provider_platform_interface 1.0.2
platform 2.2.1
plugin_platform_interface 1.0.2
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
http ^0.12.0+3
test ^1.9.4