Implement the Audio Player Feature in Flutter using the Just Audio package. This guide will walk you through the process of setting up an audio player, controlling playback, and even seeking through the audio track. Whether you’re a seasoned Flutter developer or just starting out, this will help you master the art of audio playback in your Flutter applications.
Step 1: Setting Up the Just Audio Package
First things first, we need to add the Just Audio package to our project. This package is a powerful tool for handling audio playback in Flutter, making it easy to implement features like play, pause, and seek.
dependencies:
just_audio: ^0.9.17
After adding the package to your pubspec.yaml
file, run flutter pub get
to install it.
Step 2: Changing the Class to StatefulWidget
To interact with the audio player, we need to change our class from StatelessWidget
to StatefulWidget
. This allows us to maintain the state of the audio player throughout the lifecycle of our widget.
class AudioPlayerWidget extends StatefulWidget {
@override
_AudioPlayerWidgetState createState() => _AudioPlayerWidgetState();
}
Step 3: Defining an Instance of the Audio Player
Inside our StatefulWidget
, we’ll define an instance of the audio player. This instance will be used to control the playback of our audio.
class _AudioPlayerWidgetState extends State<AudioPlayerWidget> {
late AudioPlayer _audioPlayer;
@override
void initState() {
super.initState();
_audioPlayer = AudioPlayer();
}
}
Step 4: Formatting Duration for Display
To display the elapsed time of the audio in a user-friendly format, we’ll create a function called formatDuration
. This function takes the duration in milliseconds and converts it into a string that shows minutes and seconds.
String formatDuration(Duration duration) {
final minutes = duration.inMinutes.toString().padLeft(2, '0');
final seconds = (duration.inSeconds % 60).toString().padLeft(2, '0');
return '$minutes:$seconds';
}
Step 5: Handling Play and Pause
To control the playback, we’ll create a function called handlePlayPause
. This function checks if the audio is currently playing. If it is, it pauses the audio; if it’s not, it plays the audio.
void handlePlayPause() {
if (_audioPlayer.playing) {
_audioPlayer.pause();
} else {
_audioPlayer.play();
}
}
Step 6: Seeking Through the Audio
To allow users to seek through the audio, we’ll create a function called handleSeek
. This function takes a value (in seconds) and seeks to that position in the audio.
void handleSeek(double value) {
_audioPlayer.seek(Duration(seconds: value.toInt()));
}
Step 7: Setting Up the Audio URL
To play audio from the internet or from local assets, we’ll use the setUrl
or setAsset
method of the audio player.
_audioPlayer.setUrl('https://example.com/audio.mp3');
// or
_audioPlayer.setAsset('assets/audio.mp3');
If the audio file you want is from the Internet, then you should select the `audioPlayer.setUrl()` method. If you want to choose the audio file from the gallery or assets, then you can use the `setAsset()` method.
Step 8: Implementing the Slider
To allow users to seek through the audio, we’ll implement a slider. We’ll use the positionStream
to update the slider’s value in real-time and the durationStream
to display the total duration of the audio.
StreamBuilder<Duration>(
stream: _audioPlayer.positionStream,
builder: (context, snapshot) {
final position = snapshot.data ?? Duration.zero;
return Slider(
value: position.inSeconds.toDouble(),
min: 0.0,
max: _audioPlayer.duration?.inSeconds.toDouble() ?? 0.0,
onChanged: (value) => handleSeek(value),
);
},
);
Step 9: Handling Audio Completion
To reset the slider and pause the audio when it finishes playing, we’ll listen to the playerStateStream
and update the position and pause the player when the state is PlayerState.completed
.
_audioPlayer.playerStateStream.listen((playerState) {
if (playerState.processingState == ProcessingState.completed) {
setState(() {
_audioPlayer.seek(Duration.zero);
_audioPlayer.pause();
});
}
});
Full Code
import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Audio Player'),
),
body: AudioPlayerWidget(),
),
);
}
}
class AudioPlayerWidget extends StatefulWidget {
@override
_AudioPlayerWidgetState createState() => _AudioPlayerWidgetState();
}
class _AudioPlayerWidgetState extends State<AudioPlayerWidget> {
late AudioPlayer _audioPlayer;
late Stream<Duration> _positionStream;
late Stream<Duration> _durationStream;
@override
void initState() {
super.initState();
_audioPlayer = AudioPlayer();
_positionStream = _audioPlayer.positionStream;
_durationStream = _audioPlayer.durationStream;
_audioPlayer.setUrl('https://example.com/audio.mp3');
}
@override
void dispose() {
_audioPlayer.dispose();
super.dispose();
}
String formatDuration(Duration duration) {
final minutes = duration.inMinutes.toString().padLeft(2, '0');
final seconds = (duration.inSeconds % 60).toString().padLeft(2, '0');
return '$minutes:$seconds';
}
void handlePlayPause() {
if (_audioPlayer.playing) {
_audioPlayer.pause();
} else {
_audioPlayer.play();
}
}
void handleSeek(double value) {
_audioPlayer.seek(Duration(seconds: value.toInt()));
}
@override
Widget build(BuildContext context) {
return Column(
children: [
StreamBuilder<Duration>(
stream: _durationStream,
builder: (context, snapshot) {
final duration = snapshot.data ?? Duration.zero;
return Text(formatDuration(duration));
},
),
StreamBuilder<Duration>(
stream: _positionStream,
builder: (context, snapshot) {
final position = snapshot.data ?? Duration.zero;
return Slider(
value: position.inSeconds.toDouble(),
min: 0.0,
max: duration.inSeconds.toDouble(),
onChanged: (value) => handleSeek(value),
);
},
),
IconButton(
icon: Icon(_audioPlayer.playing ? Icons.pause : Icons.play_arrow),
onPressed: handlePlayPause,
),
],
);
}
}
Conclusion
By following this, you’ve learned how to implement a fully functional audio player in Flutter using the Just Audio package. We’ve covered setting up the audio player, controlling playback, seeking through the audio, and handling audio completion. This comprehensive guide should equip you with the knowledge and skills to implement audio playback in your Flutter applications.
Remember, practice is key to mastering any new technology or framework. So, feel free to experiment with this code, try different audio sources, and explore additional features of the Just Audio package.
Thank you for reading this article. If you have any questions or need further assistance, feel free to leave a comment below. Happy coding!