Creating an Flutter Audio Player

Flutter is a powerful framework for building cross-platform applications. One of the exciting features you can implement in your Flutter app is an audio player. In this post, I’ll guide you through creating a simple audio player using the audioplayers package in Flutter.

Setting Up Your Flutter Project

First, ensure you have a Flutter project set up. If you don’t have one yet, you can create a new Flutter project by running:

flutter create audio_player_app

Navigate to your project directory:

cd audio_player_app

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

dependencies:
  flutter:
    sdk: flutter
  audioplayers: ^0.20.1

Run flutter pub get to install the package.

Creating the Audio Player

Now, let’s dive into the code. We’ll create a screen that plays an MP3 audio file from a given URL.

The Mp3AudioPlayScreen Widget

Create a new file named mp3_audio_play_screen.dart and add the following code:

import 'dart:async';
import 'package:audioplayers/audioplayers.dart';
import 'package:cockpit/app/components/colors.dart';
import 'package:cockpit/app/widgets/appbar.dart';
import 'package:flutter/material.dart';
class Mp3AudioPlayScreen extends StatefulWidget {
  final String audioLink;
  const Mp3AudioPlayScreen({super.key, required this.audioLink});
  @override
  Mp3AudioPlayScreenState createState() => Mp3AudioPlayScreenState();
}
class Mp3AudioPlayScreenState extends State<Mp3AudioPlayScreen> {
  late AudioPlayer player;
  @override
  void initState() {
    super.initState();
    // Create the audio player.
    player = AudioPlayer();
    // Set the release mode to keep the source after playback has completed.
    player.setReleaseMode(ReleaseMode.stop);
    // Start the player as soon as the app is displayed.
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      await player.setSource(UrlSource(widget.audioLink));
      await player.resume();
    });
  }
  @override
  void dispose() {
    // Release all sources and dispose the player.
    player.dispose();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      appBar: AppBarWidget(),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            PlayerWidget(player: player),
          ],
        ),
      ),
    );
  }
}

The PlayerWidget

Next, we’ll create the PlayerWidget to handle the playback controls and display the audio status.

Add the following code to the same file or create a new file for PlayerWidget:

class PlayerWidget extends StatefulWidget {
final AudioPlayer player;

const PlayerWidget({required this.player, super.key});

@override
State<StatefulWidget> createState() => _PlayerWidgetState();
}

class _PlayerWidgetState extends State<PlayerWidget> {
PlayerState? _playerState;
Duration? _duration;
Duration? _position;

StreamSubscription? _durationSubscription;
StreamSubscription? _positionSubscription;
StreamSubscription? _playerCompleteSubscription;
StreamSubscription? _playerStateChangeSubscription;

bool get _isPlaying => _playerState == PlayerState.playing;
bool get _isPaused => _playerState == PlayerState.paused;
String get _durationText => _duration?.toString().split('.').first ?? '';
String get _positionText => _position?.toString().split('.').first ?? '';
AudioPlayer get player => widget.player;

@override
void initState() {
super.initState();
// Use initial values from player
_playerState = player.state;
player.getDuration().then((value) => setState(() { _duration = value; }));
player.getCurrentPosition().then((value) => setState(() { _position = value; }));
_initStreams();
}

void _initStreams() {
_durationSubscription = player.onDurationChanged.listen((duration) {
setState(() => _duration = duration);
});

_positionSubscription = player.onPositionChanged.listen((position) {
setState(() => _position = position);
});

_playerCompleteSubscription = player.onPlayerComplete.listen((event) {
setState(() {
_position = _duration;
_playerState = PlayerState.completed;
});
});

_playerStateChangeSubscription = player.onPlayerStateChanged.listen((state) {
setState(() => _playerState = state);
});
}

@override
void dispose() {
_durationSubscription?.cancel();
_positionSubscription?.cancel();
_playerCompleteSubscription?.cancel();
_playerStateChangeSubscription?.cancel();
super.dispose();
}

@override
Widget build(BuildContext context) {
final Color playColor = _isPlaying ? darkRedColor : whiteColor100.withOpacity(0.8);
final Color pauseColor = _isPaused ? darkRedColor : whiteColor100.withOpacity(0.8);
final Color stopColor = (!_isPlaying && !_isPaused) ? darkRedColor : whiteColor100.withOpacity(0.8);

return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: Icon(Icons.play_arrow, color: playColor),
onPressed: _isPlaying ? null : () => player.resume(),
),
IconButton(
icon: Icon(Icons.pause, color: pauseColor),
onPressed: _isPlaying ? () => player.pause() : null,
),
IconButton(
icon: Icon(Icons.stop, color: stopColor),
onPressed: () => player.stop(),
),
],
),
Text(_positionText + ' / ' + _durationText),
],
);
}
}

Explanation

  1. Mp3AudioPlayScreen: This widget initializes the AudioPlayer and starts playing the audio as soon as the widget is displayed.
  2. PlayerWidget: This widget provides the playback controls (play, pause, stop) and displays the current position and duration of the audio.

Using the Widgets

Finally, use the Mp3AudioPlayScreen widget in your main application file to see it in action. Replace the MyHomePage widget with Mp3AudioPlayScreen and provide an audio URL.

import 'package:flutter/material.dart';
import 'mp3_audio_play_screen.dart';
void main() {
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Audio Player',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const Mp3AudioPlayScreen(audioLink: 'https://www.example.com/audio.mp3'),
    );
  }
}

Free Audio for the testing –

Screenshot of a Flutter app with an audio player interface

Leave a Reply

Your email address will not be published. Required fields are marked *

Awesome Work

You May Also Like