Using the audioplayers Package in Flutter

Flutter is a powerful framework for building cross-platform mobile applications, and incorporating audio playback is a common requirement for many apps. The audioplayers package in Flutter provides an easy-to-use solution for adding audio playback capabilities to your Flutter application. This article will guide you through the process of using the audioplayers package, covering everything from installation to advanced playback features.

What is the audioplayers Package?

The audioplayers package is a Flutter plugin that allows you to play audio files from various sources, including local files, assets, and URLs. It supports multiple platforms, including Android, iOS, web, and desktop, making it a versatile choice for cross-platform audio playback.

Why Use audioplayers?

  • Cross-Platform Support: Works seamlessly on Android, iOS, web, and desktop.
  • Easy Integration: Provides a simple API for common audio playback tasks.
  • Multiple Sources: Supports audio files from local storage, assets, and remote URLs.
  • Customizable: Offers options to control volume, playback rate, loop mode, and more.
  • Event Handling: Provides event listeners for playback state changes, duration updates, and more.

How to Implement Audio Playback with audioplayers in Flutter

Step 1: Add the Dependency

First, add the audioplayers package to your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  audioplayers: ^5.2.1 # Use the latest version

Then, run flutter pub get in your terminal to install the package.

Step 2: Import the Package

In your Dart file, import the audioplayers package:

import 'package:audioplayers/audioplayers.dart';

Step 3: Basic Audio Playback

Create an instance of AudioPlayer and use it to play an audio file:

import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Audio Players Demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final player = AudioPlayer();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Audio Players Demo'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            // Play audio from a URL
            await player.play(UrlSource('https://www.example.com/audio.mp3'));
          },
          child: Text('Play Audio'),
        ),
      ),
    );
  }

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

In this example, the audio file is played from a URL. Remember to replace 'https://www.example.com/audio.mp3' with a valid URL to an audio file.

Step 4: Playing Audio from Assets

To play audio from assets, you first need to add the audio file to your assets folder. Then, update your pubspec.yaml file to include the asset:

flutter:
  assets:
    - assets/audio/

Make sure to create an audio folder inside the assets directory and place your audio file there (e.g., assets/audio/audio.mp3).

Now, you can play the audio file from your assets:

ElevatedButton(
  onPressed: () async {
    // Play audio from assets
    await player.play(AssetSource('audio/audio.mp3'));
  },
  child: Text('Play Audio from Assets'),
),

Step 5: Controlling Audio Playback

The audioplayers package provides methods to control audio playback:

  • Pause: player.pause()
  • Resume: player.resume()
  • Stop: player.stop()
  • Seek: player.seek(Duration(seconds: 10))
  • Set Volume: player.setVolume(0.5) (0.0 to 1.0)
  • Set Rate: player.setPlaybackRate(1.5) (adjust playback speed)
  • Set Loop Mode: player.setReleaseMode(ReleaseMode.loop)

Here’s an example of implementing these controls:

import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Audio Players Demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final player = AudioPlayer();
  bool isPlaying = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Audio Players Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: () async {
                if (isPlaying) {
                  await player.pause();
                  setState(() {
                    isPlaying = false;
                  });
                } else {
                  await player.play(AssetSource('audio/audio.mp3'));
                  setState(() {
                    isPlaying = true;
                  });
                }
              },
              child: Text(isPlaying ? 'Pause' : 'Play'),
            ),
            ElevatedButton(
              onPressed: () async {
                await player.stop();
                setState(() {
                  isPlaying = false;
                });
              },
              child: Text('Stop'),
            ),
            ElevatedButton(
              onPressed: () async {
                await player.seek(Duration(seconds: 10));
              },
              child: Text('Seek to 10s'),
            ),
            ElevatedButton(
              onPressed: () async {
                await player.setVolume(0.5);
              },
              child: Text('Set Volume to 50%'),
            ),
            ElevatedButton(
              onPressed: () async {
                await player.setPlaybackRate(1.5);
              },
              child: Text('Set Playback Rate to 1.5x'),
            ),
            ElevatedButton(
              onPressed: () async {
                await player.setReleaseMode(ReleaseMode.loop);
              },
              child: Text('Set Loop Mode'),
            ),
          ],
        ),
      ),
    );
  }

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

Step 6: Handling Audio Player Events

The audioplayers package provides event listeners to monitor playback state and other events:

  • onPlayerComplete: Triggered when the audio finishes playing.
  • onDurationChanged: Provides updates on the audio duration.
  • onPositionChanged: Provides updates on the current playback position.
  • onPlayerStateChanged: Provides updates on the player state (playing, paused, stopped).
  • onError: Reports any errors that occur during playback.

Here’s an example of how to use these event listeners:

import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Audio Players Demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final player = AudioPlayer();
  Duration? _duration;
  Duration? _position;
  PlayerState _playerState = PlayerState.stopped;

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

  void setAudioPlayerListeners() {
    player.onPlayerComplete.listen((event) {
      setState(() {
        _playerState = PlayerState.stopped;
        _position = Duration.zero;
      });
    });

    player.onDurationChanged.listen((Duration d) {
      setState(() => _duration = d);
    });

    player.onPositionChanged.listen((Duration p) {
      setState(() => _position = p);
    });

    player.onPlayerStateChanged.listen((PlayerState s) {
      setState(() => _playerState = s);
    });

    player.onError.listen((msg) {
      print('Audio Player Error: $msg');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Audio Players Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('Duration: ${_duration?.toString() ?? 'Unknown'}'),
            Text('Position: ${_position?.toString() ?? '0:00'}'),
            Text('State: $_playerState'),
            ElevatedButton(
              onPressed: () async {
                if (_playerState == PlayerState.playing) {
                  await player.pause();
                } else {
                  await player.play(AssetSource('audio/audio.mp3'));
                }
              },
              child: Text(_playerState == PlayerState.playing ? 'Pause' : 'Play'),
            ),
          ],
        ),
      ),
    );
  }

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

Advanced Usage

The audioplayers package supports more advanced features:

  • Streamed Mode: Play large audio files efficiently by using PlayerMode.LOW_LATENCY (better for short clips and sound effects) or PlayerMode.MEDIA_PLAYER (more efficient for larger tracks)
  • Simultaneous Playback: Use multiple AudioPlayer instances to play multiple sounds simultaneously.
  • Platform-Specific Settings: Configure platform-specific settings (like audio session configurations on iOS).

Example for changing the player mode

ElevatedButton(
  onPressed: () async {
    // set to streamed mode. 
    await player.setPlayerMode(PlayerMode.mediaPlayer);
    await player.play(AssetSource('audio/audio.mp3'));
  },
  child: Text('Stream from file'),
)

Conclusion

The audioplayers package simplifies the integration of audio playback functionality in Flutter applications. With its cross-platform support, easy-to-use API, and extensive features, it’s a great choice for adding audio capabilities to your projects. Whether you’re building a music player, a podcast app, or any application requiring audio playback, audioplayers offers the flexibility and control you need.