Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Music Player Using Flutter

Things that you may likely learn from the Blog :

Before starting the blog let me tell you what you can learn from this blog:-

In this blog, you will learn how to implement a music player into your flutter app.

  • How to fetch the music from external storage, play from assets file , how to play the music using a URL(internet).
  • Controlling the volume of the music player.
  • How to pause and play the song.

Demo of App ::

DEMO.gif: {Working gif of module}

Video :

new.mp4
Edit descriptiondrive.google.com


Introduction

Music is a language of emotions. Music apps have become an apparent hit and need of the times. Users are using different music apps to listen up to their favourite songs to help them relieve stress or in Improving their creative ability.

As an app developer, you must make some apps that you can use in your daily life. So I tried to make a personal music app, hoping that you will also like it. In this blog, I will help you to build your basic music app using flutter.😊😊

Table of content::

  1. Packages used
  2. Setting up the project
  3. Playing music using the internet and assets
  4. Fetching music files from our external storage.
  5. Setting up the audio
  6. Creating a Control panel
  7. GitHub Link

Packages used::

We will use flutter_audio_query to fetch the music form our external storage(eg. mobile phone, memory card, etc).

flutter_audio_query | Flutter Package
A Flutter plugin, Android only at this moment, that allows you query for audio metadata info about artists, albums…pub.dev

audio_manager package provides us various methods and functions to implement functionality in our app such as play, pause, seek, inc. or dec. volume.

audio_manager | Flutter Package
A flutter plugin for music playback, including notification handling. This plugin is developed for iOS-based on…pub.dev

Setting up the project::

import the packages

import 'package:flutter_audio_query/flutter_audio_query.dart';
import 'package:audio_manager/audio_manager.dart';

Modify your AndroidManifest.xml

<application
...
android:usesCleartextTraffic="true"
...
>

Modify your build.gradle file.

defaultConfig {
minSdkVersion 23
}

Playing music using internet and assets::

Creating an audio manager instance

var audioManagerInstance = AudioManager.instance;

Playing music using the start method

AudioManager provides us start() method to play the music. It takes a URL, title, description, cover, and auto.

onTap: () {
audioManagerInstance
.start("song URL", "song title",
desc: "description",
auto: true,
cover: "cover URL")
.then((err) {
print(err);
});
},

To play the music file using assets file you just need to change the song URL to assets file path.

onTap: () {
audioManagerInstance
.start("assets/music.mp3"song title",
desc: "description",
auto: true,
cover: "assets/cover.png")
.then((err) {
print(err);
});
},

Fetching music files from our external storage::

To fetch the music files form the external storage we will use a FutureBuilder as FlutterAudioQuery returns a future . This class provides us various methods such as getSongs, getSongsFromArtist , getSongsFromAlbum , getSongsFromArtistAlbum , etc.

To keep the logic simple and sleek we will only use getSongs method. You can use as many as you want.

FutureBuilder(
future: FlutterAudioQuery()
.getSongs(sortType: SongSortType.RECENT_YEAR),
builder: (context, snapshot) {
List<SongInfo> songInfo = snapshot.data;
if (snapshot.hasData) return SongWidget(songList: songInfo);
return Container(
height: MediaQuery.of(context).size.height * 0.4,
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircularProgressIndicator(),
SizedBox(
width: 20,
),
Text(
"Loading....",
style: TextStyle(fontWeight: FontWeight.bold),
)
],
),
),
);
},
)

SongWidget

To play the music from the external memory we require a path of that song. SongInfo class provides us filePath property to get the path of the music file.

onTap: () {
audioManagerInstance
.start("file://${song.filePath}", song.title,
desc: song.displayName,
auto: true,
cover: song.albumArtwork)
.then((err) {
print(err);
});
},

https://gist.github.com/anmolseth06/11a33c09b1b4f085494835b1b55bb263#file-songwidget-dart

Setting up the audio::

This is the most important part, because this contolles various events of audio.

void setupAudio() {
audioManagerInstance.onEvents((events, args) {
switch (events) {
case AudioManagerEvents.start:
_slider = 0;
break;
case AudioManagerEvents.seekComplete:
_slider = audioManagerInstance.position.inMilliseconds /
audioManagerInstance.duration.inMilliseconds;
setState(() {});
break;
case AudioManagerEvents.playstatus:
isPlaying = audioManagerInstance.isPlaying;
setState(() {});
break;
case AudioManagerEvents.timeupdate:
_slider = audioManagerInstance.position.inMilliseconds /
audioManagerInstance.duration.inMilliseconds;
audioManagerInstance.updateLrc(args["position"].toString());
setState(() {});
break;
case AudioManagerEvents.ended:
audioManagerInstance.next();
setState(() {});
break;
default:
break;
}
});
}

initializing setupAudio

void initState() {
super.initState();
setupAudio();
}

Creating a control pannel::

This panel has a playpause button, previous button, next button, and a songProgress Slider .

Widget bottomPanel() {
return Column(children: <Widget>[
Padding(
padding: EdgeInsets.symmetric(horizontal: 16),
child: songProgress(context),
),
Container(
padding: EdgeInsets.symmetric(vertical: 16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
CircleAvatar(
child: Center(
child: IconButton(
icon: Icon(
Icons.skip_previous,
color: Colors.white,
),
onPressed: () => audioManagerInstance.previous()),
),
backgroundColor: Colors.cyan.withOpacity(0.3),
),
CircleAvatar(
radius: 30,
child: Center(
child: IconButton(
onPressed: () async {
if(audioManagerInstance.isPlaying)
audioManagerInstance.toPause();
audioManagerInstance.playOrPause();
},
padding: const EdgeInsets.all(0.0),
icon: Icon(
audioManagerInstance.isPlaying
? Icons.pause
: Icons.play_arrow,
color: Colors.white,
),
),
),
),
CircleAvatar(
backgroundColor: Colors.cyan.withOpacity(0.3),
child: Center(
child: IconButton(
icon: Icon(
Icons.skip_next,
color: Colors.white,
),
onPressed: () => audioManagerInstance.next()),
),
),
],
),
),
]);
}

Song Duration

This function is used to format the duration of the song this is in millisecond format, we will convert it into this format 00:00 .

Here format is a string 00:00 . _formatDuration takes the duration of the song. If the duration is null then it returns — : — otherwise it returns the duration in the given format.

String _formatDuration(Duration d) {
if (d == null) return "--:--";
int minute = d.inMinutes;
int second = (d.inSeconds > 60) ? (d.inSeconds % 60) : d.inSeconds;
String format = ((minute < 10) ? "0$minute" : "$minute") +
":" +
((second < 10) ? "0$second" : "$second");
return format;
}

SongProgress

Widget songProgress(BuildContext context) {
var style = TextStyle(color: Colors.black);
return Row(
children: <Widget>[
Text(
_formatDuration(audioManagerInstance.position),
style: style,
),
Expanded(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 5),
child: SliderTheme(
data: SliderTheme.of(context).copyWith(
trackHeight: 2,
thumbColor: Colors.blueAccent,
overlayColor: Colors.blue,
thumbShape: RoundSliderThumbShape(
disabledThumbRadius: 5,
enabledThumbRadius: 5,
),
overlayShape: RoundSliderOverlayShape(
overlayRadius: 10,
),
activeTrackColor: Colors.blueAccent,
inactiveTrackColor: Colors.grey,
),
child: Slider(
value: _slider ?? 0,
onChanged: (value) {
setState(() {
_slider = value;
});
},
onChangeEnd: (value) {
if (audioManagerInstance.duration != null) {
Duration msec = Duration(
milliseconds:
(audioManagerInstance.duration.inMilliseconds *
value)
.round());
audioManagerInstance.seekTo(msec);
}
},
)),
),
),
Text(
_formatDuration(audioManagerInstance.duration),
style: style,
),
],
);
}

Github link::

flutter-devs/music_app_demo
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com


If you find anything that could be improved please let me know, I would love to improve.💙

If this article has helped you a bit and found interesting please clap!👏


Feel free to connect with us:
And read more articles from FlutterDevs.com

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

Leave comment

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