Using MediaPlayer to play an audio file in your Android app

What will you learn?

  1. Using MediaPlayer to create an audio object
  2. Adding files to your project’s resources.
  3. Use basic controls like, play, pause, and stop. 

Building the interface

In this application, we require three buttons. Each of them will have a different purpose. The three buttons will be to play the sound, pause it, and stop it.

For our ease of use, we will add the linear layout first and drop the three buttons inside it.

If you have forgotten about the different layouts that come with Android studio, then refresh your memory by reading it again.

Once you highlight the button, by clicking on it, the properties panel will come up. Here you have to edit the IDs, the text, and the onClick() function.

  1. Edit the IDs of those buttons to btnPlay, btnPause, and btnStop. It’s always better to be uniform while naming your application elements.
  2. Edit the text by giving it the simple name of Play, Pause, and Stop.
  3. Edit the onClick function to playSong, pauseSong, and stopSong.

That’s it for the design part.

Here’s an image of the interface along with the XML code.

The code:

Adding the demo sound file to your app

Once we are done with our interface, we have to add the audio file to our project.

You have to add the files to the raw folder. You can find it here app > res > raw. If there is no raw folder then create it by right-clicking on res > new > directory. Give the directory the name raw, and nothing else.

Inside this directory, all your audio files will be present. You can not simply drag and drop files here, you have to copy your source file, then right-click on the raw directory and click paste. The following popup will appear.

You have to make sure that the new name you are giving contains all small alphabets. The only valid characters for the name in any file will be [a-z; 0-9; _].

If another popup comes asking you to verify the file type, then select the option text. As long as you have given the correct file type in the name, Android will compile it as the file type you specified, mp3 in this case.

Why are special characters not allowed in Android File Names?

Special characters are not allowed, except the underscore symbol. This is because each file inside the folder is translated into java field name inside R.java class:

drawable/icon.png -> R.drawable.icon

And since special characters are not allowed in Java names, they can’t be used. As for the capital letters, theories suggest that it is made so because of Linux and Windows. Linux treats icon.png and Icon.png as two different files and Windows treats it as one file. So to avoid any compile time error, we aren’t allowed to use capital letters either in file names.

Add at least two audio files to your project, once you are done with that, we can start writing the code in MainActivity.java file.

Coding the functionality

As with all apps, we begin our coding in Java. First, we need to instantiate the MediaPlayer class. This will create an object of the class:

MediaPlayer mp;

What is basically happening here is that we have created an object mp of the class MediaPlayer. This means that all the properties of the class MediaPlayer are stored in this object.

Once you instantiate the MediaPlayer class, the package android.media.MediaPlayer will get automatically added to your code. If it doesn’t then do it anywhere near the other imports like this:

import android.media.MediaPlayer;

Adding the audio file to this object

We want this code to run as soon as the app launches. So we’ll place it in the onCreate function:

mp = MediaPlayer.create(this, R.raw.abc);

Just make sure that instead of ‘abc’ you mention the name you had given to your file. You don’t need to add ‘.mp3’ or ‘.wav’ or whatever filetype you are using.

Playing the sound

Now we have to define the function we are calling when we hit the play button.

MediaPlayer has an inbuilt function called start( ). We’ll use that to our advantage.

public void playSong(View v){
    mp.start();
}

Now, if everything is in order then the audio file would start playing.

Pausing the sound

If instead of some sound effect, you added a full-length song then you have to add a way to pause the song.

Fortunately, MediaPlayer has an inbuilt function called pause( ) which we will run when we hit the pause button.

public void pauseSong(View v) {
    mp.pause();
}

Now, if everything is in order then the audio file would pause. Hitting up the Play button will start the file from where it was paused.

Stopping the sound

Stopping the file will completely stop the file and you won’t be able to run it again.

MediaPlayer has an inbuilt function called stop( ).

public void stopSong(View v) {
    mp.stop();
}

Now when you hit the Play button again, nothing happens. This is because the MediaPlayer object has been cleared. There is no file present in the object anymore. So in the same function, add another line of code.

mp = MediaPlayer.create(this, R.raw.abcd);

This time, add the second file name to avoid confusion.

Run your app to test it. If you have forgotten how to set up your virtual device, then refresh your memory be going through the post again.

Note: The files are stored in the app, so if you add audio files of size larger than 100mb, then your app size would be larger than 100mb.

Checkout some more of our tutorials on Android.

Use Intent to start a new activity

2 Simple Calculator App

3 Weight Conversion app

4 Study about different Layouts in Android and which one to use when.

The completed code of the Java file looks like this:

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.