How To Build a Music Player Android App - Hive Programmers
Greetings to my favorite Science community online, StemSocial.
It's @skyehi and I'm back to continue my series on Android App development tutorials for beginners.
In today's really special episode, we're go to work on a music player App. I looked through the past episodes and realized that I've not made a tutorial on an App as useful as a music player App.
Original Image Source by Tom Swinnen from Pexels
By going through with this particular tutorial, I'll be able to introduce to everyone some cool new music related APIs on Android and how to integrate them to build a music player App.
It's still going to be a basic tutorial so we won't do too much technical and complex stuff. I'll keep it as simple as I possibly can guys.
Alright without wasting anymore time, let's get started with our work.
Prerequisites
As always, for the newcomers sake, I'll talk about the Prerequisites.
Android Studio IDE - This is the software on which we'll build all our Android Apps. Please ensure that it's been properly installed on your PC.
Java Development Kit, JDK - You need to correctly install JDK on your PC so that your PC can successfully execute any Java code or command you give it
Android Device or Emulator - After developing the music player App, we would need to test the app either on a physical Android device or an emulator
Audio files (MP3) for testing - Now for this particular tutorial , ensure that the device you'll be testing the music player App on has some MP3 audio or music files to play.
If you have all these prerequisites checked out, you're good to go with this tutorial guys.
Creating A New Android Studio Project
The first thing you would want to do to build the music player App is to open Android Studio application and click on "Create a New Project".
You will be shown a list of project template options to choose from. I'll always recommend choosing the "Empty Activity" template for your project because this is a beginner's guide and we would want to keep things simple.
When you're through with that, click on the "Next" button and configure your other project details like the App name and package name.
Also guys, as always do not forget to set Java as the programming language for the project and not Kotlin. We'll be building our backend or logic code using Java so please select that instead.
When you're through with the project configuration details, please click on the "Finish" button, sit back and let Android Studio prepare your new project space.
Designing the User Interface
Alright guys, it's time to work on the Frontend or User Interface, UI of your music player App.
The design layout code of our App will be written with XML language inside our res/layout/activity_main.xml
file.
So guys go ahead and open that layout file and design the music player interface.
Now speaking of the design, a Music player app usually has these four basic elements.
A Button
for playing the song, button for pausing the song, another button for stopping the entire song and lastly a SeekBar
to control the progress or skipping of the song either forward or backwards.
Since I would want to keep it simple, I would not include other features like, next Song, now playing, favorites, share, delete and many other features that makes for a great music player App.
We'll start by learning the basics and as we make progress in this series, I'll introduce you to more advanced levels of building Android Apps.
I hope you're excited for that's guys.
Here's how your design layout code should look like
(html comment removed: activity_main.xml )
<Button
android:id="@+id/btnPlay"
android:text="Play"
android:onClick="onPlayClick" />
<Button
android:id="@+id/btnPause"
android:text="Pause"
android:onClick="onPauseClick" />
<Button
android:id="@+id/btnStop"
android:text="Stop"
android:onClick="onStopClick" />
<SeekBar
android:id="@+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onSeekBarClick"/>
Handling Media Playback
It's time to handle the playing of the music or audio. Thankfully Android studio comes with an inbuilt API class for playing songs and it's called android.media.MediaPlayer
.
To handle Media playback we need to open MainActivity.java
, import and initialize the MediaPlayer
API so our music player App can be capable of playing audio or music.
Afterwards, we would also need to implement methods for playing, pausing, stopping audio, and also updating the SeekBar.
This is where the real logic code of our App will be written.
Here's how your logic code should look like
// MainActivity.java
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.SeekBar;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private MediaPlayer mediaPlayer;
private SeekBar seekBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer = MediaPlayer.create(this, R.raw.your_audio_file);
seekBar = findViewById(R.id.seekBar);
seekBar.setMax(mediaPlayer.getDuration());
mediaPlayer.setOnCompletionListener(mp -> onStopClick(null));
}
public void onPlayClick(View view) {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
updateSeekBar();
}
}
public void onPauseClick(View view) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
}
public void onStopClick(View view) {
if (mediaPlayer.isPlaying() || mediaPlayer.getCurrentPosition() > 0) {
mediaPlayer.seekTo(0);
mediaPlayer.pause();
}
}
private void updateSeekBar() {
seekBar.setProgress(mediaPlayer.getCurrentPosition());
if (mediaPlayer.isPlaying()) {
Runnable runnable = this::updateSeekBar;
seekBar.postDelayed(runnable, 1000);
}
}
public void onSeekBarClick(View view) {
if (mediaPlayer.isPlaying()) {
seekBar.setMax(mediaPlayer.getDuration());
int progress = seekBar.getProgress();
mediaPlayer.seekTo(progress);
}
}
}
Implementing SeekBar
We're through with the actual media playback Logic but we need to also link the SeekBar we created in activity_main.xml
to the Java code and use it to adjust the playback position of the audio.
This will also be done inside our MainActivity.java
file.
We have already initialized it so we only need to use the seekBar.setProgress
method to link to Java and the onSeekBarClick
method to determine what happens when a user presses the Seek Bar.
So guys I'll rewrite the MainActivity.java
code but this time I'll include the updated Seekbar code.
Here's how your code should look like
// MainActivity.java
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.SeekBar;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private MediaPlayer mediaPlayer;
private SeekBar seekBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer = MediaPlayer.create(this, R.raw.your_audio_file);
seekBar = findViewById(R.id.seekBar);
seekBar.setMax(mediaPlayer.getDuration());
mediaPlayer.setOnCompletionListener(mp -> onStopClick(null));
// Add this line to update SeekBar position while playing
mediaPlayer.setOnPreparedListener(mp -> updateSeekBar());
}
// Other methods remain the same
private void updateSeekBar() {
seekBar.setProgress(mediaPlayer.getCurrentPosition());
if (mediaPlayer.isPlaying()) {
Runnable runnable = this::updateSeekBar;
seekBar.postDelayed(runnable, 1000);
}
}
public void onSeekBarClick(View view) {
if (mediaPlayer.isPlaying()) {
seekBar.setMax(mediaPlayer.getDuration());
int progress = seekBar.getProgress();
mediaPlayer.seekTo(progress);
}
}
}
Requesting Permissions
We're basically through with our entire music player App but we need not forget one very important thing, requesting permission.
For a music player App, it would definitely need access to the Android device's external storage to retrieve all audio or Mp3 files there and play it.
So we need to request permission in our App to access storage by using READ_EXTERNAL_STORAGE
Of course, the permission request code will be written inside our AndroidManifest.xml
file.
Here's how your permission request code should look like
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.musicplayer">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application>
(html comment removed: App components and configuration go here )
</application>
</manifest>
Running Your App
Congratulations guys, you have completed your first Android music Player App. I hope you're ready to test the App now.
As always, you can run your app on an emulator or a physical Android device.
When the App launches, test the play, pause, stop, and seek functionalities. Press the play button and it will randomly pick an audio file in your device storage and start playing.
Enjoy the songs guys.
Thank you so much for taking the time to read today's blog. I hope you enjoyed this one guys.
Thanks everyone for the support and my friends @stickupcurator or @stickupboys
Have a Great Day and Catch you Next Time on StemSocial. Goodbye
You Can Follow Me @skyehi For More Like This And Others
Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!
Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).
Thanks for including @stemsocial as a beneficiary, which gives you stronger support.