flutter_audio_service 0.3.1

  • Readme
  • Changelog
  • Example
  • Installing
  • 64

flutter_audio_service #

A Flutter plugin by Tailosive Development (@TailosiveDev) created by Karol WÄ…sowski (@KarolWasowski) Licensed under the BSD License

This package was first released as flutter_audio_as_service, but was later renamed because of issues with pub.dev

The plugin is Android only as of now.

1. Before you begin #

Add this permission to AndroidManifest.xml:

<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

Make sure your app uses Java8 by adding this code into your app-level build.gradle into the android section:

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

Enable androidx support in your app.

Add the service to AndroidMainfest.xml

<manifest>
  ...
  <application>
    ...
    ...
    <service 
      android:name="net.tailosive.flutter_audio_as_service.AudioService"/>
  </application>
</manifest>

2. Usage #

To start playback initialize the player with the following:

AudioInfo info = AudioInfo(
  "Title",
  "Author",
  audioUrl,
  coverUrl,
  drawableAppIcon
)

FlutterAudioAsService.init(info);

audioUrl and coverUrl are strings - could be both urls or a file directories (file:///)

How to properly set appIcon

  • put the desired .png image into android/src/main/res/drawable/
  • if your resource is app_icon.png then set the appIcon value to be "app_icon"
  • the value can be null

If you wish you can set event listeners as follows:

AudioPlayerListener listener = AudioPlayerListener(
  onPlayerStateChanged: (PlayerState playerState) {
    print(playerState);
  },
  onPlayerPositionChanged: (Duration playerPosition) {
    print(playerPosition.toString());
  },
  onPlayerCompleted: () {
    print("Player completed");
  }
);

FlutterAudioAsService.setListeners(listener);

Playback is controlled with the following functions:

FlutterAudioAsService.pause();
FlutterAudioAsService.resume();

During playback you may also seek with:

FlutterAudioAsService.seekBy(Duration(seconds: 30));
FlutterAudioAsService.seekTo(Duration(minutes: 15, seconds: 47));

To stop playback and destroy the service run:

FlutterAudioAsService.stop();

3. Features #

The plugin supports audio playback as an Android service with caching functionality included. It uses ExoPlayer with MediaSession API and rich notification controls.

0.3.1 #

  • Renamed plugin to flutter_audio_service - setup is still the same

0.3.0 #

  • Bug fixes
  • Implementation changes
  • Tested offline audio and albumCover source
  • Added abbility to set a different albumCover for each song
  • Updated everything to be on par with how things are done now

0.2.1 #

  • Stability improvements

0.2.0 #

  • The service now gets bound to the flutter app and unbinds automatically. This improves background performance and stability

0.1.3 #

  • Updated documentation

0.1.2 #

  • Updated example
  • Fixed seekTo() throwing error

0.1.1 #

  • Prevented running functions on null object references
  • If player initialized with source that is already playing player won't start over - it will keep playing
  • getAudioLength() now returns 0 if player is idle

0.1.0 #

Minor changes, improved consistency

0.0.4 #

Added listeners to player state changes, audio position changes and audio completed playing. This will be released as 0.1.0 after some testing.

0.0.3 #

Adds missing feature - set notification album cover, and makes the plugin release-ready (beta)

0.0.2 #

Offers basic functionality with support for starting a service and notification controls.

0.0.1 #

Offers basic playback functionality without starting a service.

example/lib/main.dart

//
//  Flutter plugin for audio playback on Android
//  Created by Karol WÄ…sowski (wasowski02@gmail.com) on June 23rd 2019
//  Licensed under the BSD License
//

import 'package:flutter/material.dart';
import 'package:flutter_audio_as_service/flutter_audio_as_service.dart';
import 'package:flutter_audio_as_service/AudioInfoClass.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Duration audioLength = Duration(milliseconds: 0);
  Duration audioPosition = Duration(milliseconds: 0);

  // See docs to find details about how to add fallback images and app icon
  AudioInfo trackDetails = AudioInfo(
    "Title", // Title
    "Author", // Artist
    "https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3", // Audio location (hhtps:// or file:///)
    "https://scdn.androidcommunity.com/wp-content/uploads/2018/02/flutter.jpeg", // Album cover (https:// or file:///)
    "app_icon" // Notification icon (drawable)
  );

  Future<void> setAudioLength() async {
    audioLength = await FlutterAudioAsService.getAudioLength();
    setState(() {
      
    });
  }

  @override
  void initState() {
    super.initState();

    AudioPlayerListener listener = AudioPlayerListener(
      onPlayerStateChanged: (PlayerState playerState) {
        if (playerState == PlayerState.idle) {
          setState(() {
            audioLength = Duration(milliseconds: 0);
            audioPosition = Duration(milliseconds: 0);
          });
        } else {
          setAudioLength();
        }
      },
      onPlayerPositionChanged: (Duration playerPosition) {
        setState(() {
          audioPosition = playerPosition;
        });
      },
      onPlayerCompleted: () {
        print("Player completed");
        audioPosition = Duration(milliseconds: 0);
        audioLength = Duration(milliseconds: 0);
      }
    );

    FlutterAudioAsService.setListeners(listener);
  }

  @override
  void dispose() {
    super.dispose();

    FlutterAudioAsService.unbind();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Android Audio playback as service'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              RaisedButton(
                child: Text("Connect to service, load audio, start playback"),
                onPressed: () async {
                  await FlutterAudioAsService.init(trackDetails);
                  setState(() {

                  });
                },
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  IconButton(
                    icon: Icon(Icons.play_arrow),
                    onPressed: () async {
                      await FlutterAudioAsService.resume();
                    },
                  ),
                  IconButton(
                    icon: Icon(Icons.pause),
                    onPressed: () async {
                      await FlutterAudioAsService.pause();
                    },
                  ),
                  IconButton(
                    icon: Icon(Icons.stop),
                    onPressed: () async {
                      await FlutterAudioAsService.stop();
                      setState(() {
                        audioLength = Duration(milliseconds: 0);
                        audioPosition = Duration(milliseconds: 0);
                      });
                    },
                  ),
                ],
              ),
              RaisedButton(
                child: Text("Seek by 30s"),
                onPressed: () async {
                  await FlutterAudioAsService.seekBy(Duration(seconds: 30));
                },
              ),
              RaisedButton(
                child: Text("Seek to end"),
                onPressed: () async {
                  await FlutterAudioAsService.seekTo(audioLength - Duration(seconds: 15));
                },
              ),
              Text("Audio length: " + audioLength.toString()),
              Text("Player progress: " + audioPosition.toString() + " / " + audioLength.toString()),
            ],
          ),
        ),
      ),
    );
  }
}

Use this package as a library

1. Depend on it

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


dependencies:
  flutter_audio_service: ^0.3.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:flutter_audio_service/AudioInfoClass.dart';
import 'package:flutter_audio_service/flutter_audio_as_service.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
29
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
64
Learn more about scoring.

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

  • Dart: 2.8.4
  • pana: 0.13.14
  • Flutter: 1.17.5

Analysis suggestions

Package does not support Flutter platform ios

Because:

  • package:flutter_audio_service/AudioInfoClass.dart that declares support for platforms: android

Package does not support Flutter platform linux

Because:

  • package:flutter_audio_service/AudioInfoClass.dart that declares support for platforms: android

Package does not support Flutter platform macos

Because:

  • package:flutter_audio_service/AudioInfoClass.dart that declares support for platforms: android

Package does not support Flutter platform web

Because:

  • package:flutter_audio_service/AudioInfoClass.dart that declares support for platforms: android

Package does not support Flutter platform windows

Because:

  • package:flutter_audio_service/AudioInfoClass.dart that declares support for platforms: android

Package not compatible with SDK dart

Because:

  • flutter_audio_service that is a package requiring null.

Health suggestions

Format lib/AudioInfoClass.dart.

Run flutter format to format lib/AudioInfoClass.dart.

Format lib/flutter_audio_as_service.dart.

Run flutter format to format lib/flutter_audio_as_service.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
path_provider ^1.6.10 1.6.11
Transitive dependencies
collection 1.14.12 1.14.13
file 5.2.1
intl 0.16.1
meta 1.1.8 1.2.2
path 1.7.0
path_provider_linux 0.0.1+2
path_provider_macos 0.0.4+3
path_provider_platform_interface 1.0.2
platform 2.2.1
plugin_platform_interface 1.0.2
process 3.0.13
sky_engine 0.0.99
typed_data 1.1.6 1.2.0
vector_math 2.0.8 2.1.0-nullsafety
xdg_directories 0.1.0
Dev dependencies
flutter_test