By the end of this tutorial, you will be able to add a music player as shown in the video in your own flutter app.
How to play an audio file in flutter?
For this tutorial, we will use two packages.
- audioplayers package - This package actually does most of the part of our tutorial. It will allow us to play audio, pause, stop & resume. You can also seek through the duration. However, for the sake of keeping the tutorial short & simple, I have excluded it.
- file_picker package - This package will allow us to pick audio (it works for other file types too) from our local storage and generate its path.
STEPS TO FOLLOW:
- Add both the package dependencies as shown here
dependencies:
flutter:
sdk: flutter
audioplayers: ^0.14.1
file_picker: ^1.2.0
- (Optional) However, it worked fine on my android device without adding any permissions but just in case you see errors piling up, try adding permissions for android and/or iOS for the file_picker plugin. You can find the permissions to be added on the package's official docs on pub.dev
- Finally, paste this entire code in your main.dart file to achieve the same results as shown in the video above.
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'AudioPlayer',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Audio Player'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool _isPlaying = false;
AudioPlayer audioPlayer;
@override
void initState() {
super.initState();
audioPlayer = AudioPlayer();
}
playAudioFromLocalStorage(path) async {
int response = await audioPlayer.play(path, isLocal: true);
if (response == 1) {
// success
} else {
print('Some error occured in playing from storage!');
}
}
pauseAudio() async {
int response = await audioPlayer.pause();
if (response == 1) {
// success
} else {
print('Some error occured in pausing');
}
}
stopAudio() async {
int response = await audioPlayer.stop();
if (response == 1) {
// success
} else {
print('Some error occured in stopping');
}
}
resumeAudio() async {
int response = await audioPlayer.resume();
if (response == 1) {
// success
} else {
print('Some error occured in resuming');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
RaisedButton(
onPressed: () {
if (_isPlaying == true) {
pauseAudio();
setState(() {
_isPlaying = false;
});
} else {
resumeAudio();
setState(() {
_isPlaying = true;
});
}
},
child:
Icon(_isPlaying ? Icons.pause : Icons.play_arrow),
color: Colors.blue,
),
RaisedButton(
onPressed: () {
stopAudio();
setState(() {
_isPlaying = false;
});
},
child: Icon(Icons.stop),
color: Colors.blue,
),
],
),
],
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
RaisedButton(
onPressed: () async {
var path =
await FilePicker.getFilePath(type: FileType.audio);
setState(() {
_isPlaying = true;
});
playAudioFromLocalStorage(path);
},
child: Text(
'Load Audio File',
style: TextStyle(color: Colors.white),
),
color: Colors.blueAccent,
),
],
),
],
),
),
);
}
}
Hope you enjoyed :) If you have any questions, drop a comment below.
Keep Fluttering!