This is my fourth tutorial for how to build a ListView based Android app. In last tutorial, I have shown an example about how to build ListView with text, image, and button. In this tutorial, I will demonstrate how to play sound with Android Mediaplayer. In my example code, I will set an event listener on the button which is put in ListView. When users click on the button, I will play the local mp3 file basing on which ListView button is clicked. After we finish, you will be able to build a Android music player which has a playlist. When users click play button in the playlist, you can play the corresponding mp3 file.

This is the 4th tutorial of my Android ListView Based App Tutorial series. The whole tutorial has 4 sessions:

Android provides a very powerful multimedia class to help us handle playing music task, the MediaPlayer which has all the functions to play a MP3 file. In Android, we can play a mp3 file in three ways:

  • Play the mp3 file as Application Resource
  • Play the mp3 file which is stored in sd card
  • Play the mp3 file over internet

Play Sound File in Android App Resource Folder

First, I will talk about how to play mp3 files from local resource. We always play some predefined sound effect in this way. For example, we may want to implement some button click sound effect or animation sound effect. In this case, we will put the audio file in application’s /res/raw folder and all these audio file will be built in the Android app. To play the sound, we must know the sound resource file name. The following example source code will show you how to play a mp3 file as app resource.

MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.music_file);
mediaPlayer.prepare();
mPlayer.start();

Android Play Sound File Stored in SD Card

In some Android applications, we may download the mp3 file from internet and save them in SD Card. In this case, we will find and play the audio file by URI. If you want to create an Android music player app, this will be the proper way to handle your music.

MediaPlayer mPlayer = new MediaPlayer();
Uri myUri = Uri.parse("file:///sdcard/mp3/example.mp3");
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setDataSource(getApplicationContext(), myUri);
mPlayer.prepare();
mPlayer.start();

Play Audio File From Playlist

Now, let’s take about a real android project. I will provide a playlist which contains a list of English word. When users click on the play button in the ListView, I will play the audio file according to the selected English word.

First of all, I am gonna add a click event listener on that play sound button in ListView. Here is how I did it:

viewHolder.voiceButton.setOnClickListener(voiceButtonClickListener);

Next, I will show you the source code about the onClickListener. In this listener, I will find out the position of the item in the ListView where I click the play button. After I get the position index of ListView, I will find the corresponding English word audio file and play it with Android MediaPlayer class.

	private OnClickListener voiceButtonClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			if (mediaPlayer == null) {
				View parentRow = (View) v.getParent();
				ListView listView = (ListView) parentRow.getParent();
				final int position = listView.getPositionForView(parentRow);

				try {
					Uri mp3 = Uri.parse("android.resource://"
							+ context.getPackageName() + "/raw/"
							+ datas.get(position).word);
					mediaPlayer = new MediaPlayer();
					mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
					mediaPlayer.setDataSource(context, mp3);
					mediaPlayer.prepare(); // might take long! (for buffering, etc)
					mediaPlayer.start();
					mediaPlayer.setOnCompletionListener(onCompletionListener);
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SecurityException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalStateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	};

The above source code is a little bit complicated, isn’t it? Don’t worry about it. I will help you to explain how these Java code works line by line. The first part is how I get the item index in the ListView when users click a button in ListView.

View parentRow = (View) v.getParent();
ListView listView = (ListView) parentRow.getParent();
final int position = listView.getPositionForView(parentRow);

After I got the exact position index, I will find the English word audio file and create an URI for that audio file.

Uri mp3 = Uri.parse("android.resource://"
	+ context.getPackageName() + "/raw/"
	+ datas.get(position).word);

Here I still put all my audio file in Android resource folder /res/raw. If your audio file is located in SD card, you may change above code like this:

Uri myUri = Uri.parse("file:///sdcard/mp3/"
        + datas.get(position).word + ".mp3");

After I have the audio file URI, I can instantiate the MediaPlayer class and play the audio file in Android. Let’s check the example code.

mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(context, mp3);
mediaPlayer.prepare(); // might take long! (for buffering, etc)
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(onCompletionListener);

Please remember that MediaPlayer may consume lots of resource in Android. Therefore, we have to keep as few MediaPlayer instance as we can. In my case, I only create a new MediaPlayer instance when users play the music. When the music stops, I will release the MediaPlayer instance immediately. That’s the reason why I add an onCompletionListener event in the end. Here is the source code of onCompletionListener.

private OnCompletionListener onCompletionListener = new OnCompletionListener() {

	@Override
	public void onCompletion(MediaPlayer mp) {
		// TODO Auto-generated method stub
		mediaPlayer.release();
		mediaPlayer = null;
	}
};

Try The Android App

You can download and install this android app from Google Play, or scan the following QR code to download and install on your android phone simply. If you feel it is helpful, please support me by clicking the banner inside the app.
button-get-it-on-google-playx200

Scan the following QR code to download this app in Google Play easy and fast.
chart

Get Full Source Code at $5.99


You will get whole Android App source code at $5.99. With this source code, you can do everything you want:

  • Feed your own content;
  • Monetize the app with your own AdMob publish id;
  • Use the source code in your own project;
  • Publish this app in your android develop account;
Previous PostNext Post

20 Comments

  1. How to put the songs to be played online, so that you dont have to store the songs in your Raw folder and storing in SD Card is not a option??

    1. You question “How to put the songs online, instead of store them in Raw Folder or SD Card?”, is it?

  2. my app connect to mysql db and it shows audio files in listview in my app fetch data from db.do you have code for this?

      1. Actually I design mysql db and I store mp3 files in it.But I don’t know how to get those files to my app in listview .Please help me. And thanks for your reply.

          1. @Long Nguyen, @satish,

            To be honest, storing the mp3 file content in the database is not a good idea. Usually, we just store the mp3 file name in the database, then load the mp3 file by http.

            If you really want to store the mp3 in the db, you can still do it. Just using normal sql query to get the data from database, then return the mp3 data to your android app.

            In the android app side, just using http request to your server.

    1. I post the source code on my page. If you want to get full project source, you can pay a small fee to get it and you will be granted with full right to use it anywhere.

  3. I would like to start a service in background with no user action, I have the mp3 file stores in a local db, so my questions are:
    1- How to start background service automatically?
    2- When should I read info from db to play mp3, and not one after the other, as a play list, just at certain time based on a schedule?
    3- Files names and where to store it?
    4- Don’t mind to pay you your fee of $5.99, but I want it to work, with this conditions
    If that is possible, please let me know.
    Thanks, and have a nice day

  4. hi James

    i just bought the sample source yesterday..
    beside .json file, can i use asset database file
    as i knew u are using .json file as your database, can i use normal db such as abc.db in asset folder ? 🙂
    thanks

    1. Of course you can. But you have to use your db file to setup the database in your application, then query the db to get data.

  5. Do you have music player android source code that store the mp3 file name and the url in the database, then query the db to show play list with download button in app?

Leave a Reply to James Liu Cancel reply

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