audioplayers 0.7.4

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • 45

AudioPlayers

A Flutter plugin to play multiple simultaneously audio files, works for Android and iOS.

Install

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

dependencies:
  audioplayers: ^0.7.4

Usage

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

    AudioPlayer audioPlayer = new AudioPlayer();

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):

  play() async {
    int result = await audioPlayer.play(url);
    if (result == 1) {
      // success
    }
  }

For a Local File, add the isLocal parameter:

  playLocal() async {
    int result = await audioPlayer.play(localPath, isLocal: true);
  }

The isLocal flag is required only because iOS makes 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

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 audioPlayer.seek(new Duration(milliseconds: 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 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.

Handlers

You can register callbacks for several event handlers, like so:

Duration Handler

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

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

Position Handler

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

  player.positionHandler = (Duration  p) => {
    print('Current position: $d');
    setState(() => duration = d);
  };

Completion Handler

This handler 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.completionHandler = () {
    onComplete();
    setState(() {
      position = duration;
    });
  };

Error Handler

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

  player.errorHandler = (msg) {
    print('audioPlayer error : $msg');
    setState(() {
      playerState = PlayerState.stopped;
      duration = new Duration(seconds: 0);
      position = new 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 keep track of the copied files so that you can replay then without delay.

You can find the full documentation for this class here.

Supported Formats

You can check a list of supported formats below:

⚠️ iOS App Transport Security

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

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

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

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

example/lib/main.dart

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 'player_widget.dart';

typedef void OnError(Exception exception);

const kUrl1 = 'http://www.rxlabz.com/labz/audio.mp3';
const kUrl2 = 'http://www.rxlabz.com/labz/audio2.mp3';

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

class ExampleApp extends StatefulWidget {
  @override
  _ExampleAppState createState() => new _ExampleAppState();
}

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

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

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

  Widget _tab(List<Widget> children) {
    return Center(
      child: Container(
        padding: EdgeInsets.all(16.0),
        child: Column(
          children: children
              .map((w) => Container(child: w, padding: EdgeInsets.all(6.0)))
              .toList(),
        ),
      ),
    );
  }

  Widget _btn(String txt, VoidCallback onPressed) {
    return ButtonTheme(
        minWidth: 48.0,
        child: RaisedButton(child: Text(txt), onPressed: onPressed));
  }

  Widget remoteUrl() {
    return _tab([
      Text('Sample 1 ($kUrl1)'),
      PlayerWidget(url: kUrl1),
      Text('Sample 2 ($kUrl2)'),
      PlayerWidget(url: kUrl2),
    ]);
  }

  Widget localFile() {
    return _tab([
      Text('File: $kUrl1'),
      _btn('Download File to your Device', () => _loadFile()),
      Text('Current local file path: $localFilePath'),
      localFilePath == null
          ? Container()
          : PlayerWidget(url: localFilePath, isLocal: true),
    ]);
  }

  Widget localAsset() {
    return _tab([
      Text('Play Local Asset \'audio.mp3\':'),
      _btn('Play', () => audioCache.play('audio.mp3')),
      Text('Loop Local Asset \'audio.mp3\':'),
      _btn('Loop', () => audioCache.loop('audio.mp3')),
      Text('Play Local Asset \'audio2.mp3\':'),
      _btn('Play', () => audioCache.play('audio2.mp3')),
    ]);
  }

  Widget advanced() {
    return _tab([
      Column(children: [
        Text('Source Url'),
        Row(children: [
          _btn('Audio 1', () => advancedPlayer.setUrl(kUrl1)),
          _btn('Audio 2', () => advancedPlayer.setUrl(kUrl2)),
        ], mainAxisAlignment: MainAxisAlignment.spaceEvenly),
      ]),
      Column(children: [
        Text('Release Mode'),
        Row(children: [
          _btn('STOP', () => advancedPlayer.setReleaseMode(ReleaseMode.STOP)),
          _btn('LOOP', () => advancedPlayer.setReleaseMode(ReleaseMode.LOOP)),
          _btn('RELEASE',
              () => advancedPlayer.setReleaseMode(ReleaseMode.RELEASE)),
        ], mainAxisAlignment: MainAxisAlignment.spaceEvenly),
      ]),
      new Column(children: [
        Text('Volume'),
        Row(children: [
          _btn('0.0', () => advancedPlayer.setVolume(0.0)),
          _btn('0.5', () => advancedPlayer.setVolume(0.5)),
          _btn('1.0', () => advancedPlayer.setVolume(1.0)),
          _btn('2.0', () => advancedPlayer.setVolume(2.0)),
        ], mainAxisAlignment: MainAxisAlignment.spaceEvenly),
      ]),
      new Column(children: [
        Text('Control'),
        Row(children: [
          _btn('resume', () => advancedPlayer.resume()),
          _btn('pause', () => advancedPlayer.pause()),
          _btn('stop', () => advancedPlayer.stop()),
          _btn('release', () => advancedPlayer.release()),
        ], mainAxisAlignment: MainAxisAlignment.spaceEvenly),
      ]),
    ]);
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 4,
      child: Scaffold(
        appBar: AppBar(
          bottom: TabBar(
            tabs: [
              Tab(text: 'Remote Url'),
              Tab(text: 'Local File'),
              Tab(text: 'Local Asset'),
              Tab(text: 'Advanced'),
            ],
          ),
          title: Text('audioplayers Example'),
        ),
        body: TabBarView(
          children: [remoteUrl(), localFile(), localAsset(), advanced()],
        ),
      ),
    );
  }
}

Use this package as a library

1. Depend on it

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


dependencies:
  audioplayers: ^0.7.4

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter packages get

Alternatively, your editor might support pub get or flutter packages 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';
  
Version Uploaded Documentation Archive
0.7.4 Aug 13, 2018 Go to the documentation of audioplayers 0.7.4 Download audioplayers 0.7.4 archive
0.7.3 Jul 25, 2018 Go to the documentation of audioplayers 0.7.3 Download audioplayers 0.7.3 archive
0.7.2 Jul 20, 2018 Go to the documentation of audioplayers 0.7.2 Download audioplayers 0.7.2 archive
0.7.1 Jul 14, 2018 Go to the documentation of audioplayers 0.7.1 Download audioplayers 0.7.1 archive
0.7.0 Jul 14, 2018 Go to the documentation of audioplayers 0.7.0 Download audioplayers 0.7.0 archive
0.6.0 Jul 11, 2018 Go to the documentation of audioplayers 0.6.0 Download audioplayers 0.6.0 archive
0.5.2 May 21, 2018 Go to the documentation of audioplayers 0.5.2 Download audioplayers 0.5.2 archive
0.5.1 May 21, 2018 Go to the documentation of audioplayers 0.5.1 Download audioplayers 0.5.1 archive
0.5.0 Feb 28, 2018 Go to the documentation of audioplayers 0.5.0 Download audioplayers 0.5.0 archive
0.4.1 Jan 3, 2018 Go to the documentation of audioplayers 0.4.1 Download audioplayers 0.4.1 archive

All 14 versions...

Popularity:
Describes how popular the package is relative to other packages. [more]
90
Health:
Code health derived from static analysis. [more]
0
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
0
Overall:
Weighted score of the above. [more]
45
Learn more about scoring.

The package version is not analyzed, because it does not support Dart 2. Until this is resolved, the package will receive a health and maintenance score of 0.

Issues and suggestions

Support Dart 2 in pubspec.yaml.

The SDK constraint in pubspec.yaml doesn't allow the Dart 2.0.0 release. For information about upgrading it to be Dart 2 compatible, please see https://www.dartlang.org/dart-2#migration.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.50.0 <2.0.0