Android Mediaplayer Example – Play from URI

In this post, we are going to discuss about how to play a music file(MP3) in Android application. Android provides extensive support for playing music and it has dedicated a class called MediaPlayer which has all the necessary methods to play, pause, stop and do more with a MP3 file.

With the help of Android MediaPlayer framework we can play audio from media files stored in/as:

  1. Application’s resources (raw resources) [Android Mediaplayer Example – Play from local resource]
  2. Standalone files in the filesystem
  3. Data stream arriving over a network connection [Android Mediaplayer Example – Play from Internet]

[pgsubscribe]

Here we will discuss about how we can play music files present locally in the system.

Before we start with developing application, download code from here to follow with the below listings.

Quick Links

Project Structure

Project creation:

  • Create new android project [File >> New >> Android Project] with project name MusicAndroidActivity2
  • Click next and select target android device version [I chose version 2.2]
  • Click next and enter package name – ‘com.prgguru.example’
  • Click finish

Code Listings

Layout XML:

Open main.xml present under /res/layout folder and replace the XML with the below one. Here we are going to create two buttons – one for playing music and other for stopping music.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:text="Playing Music from SD Card"
        android:textSize="20dp" />

    <Button
        android:id="@+id/play"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dip"
        android:text="Play" />

    <Button
        android:id="@+id/stop"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dip"
        android:text="Stop" />

</LinearLayout>

How to play audio that’s available as a local file inside a system or device

  • Place music files(s) under res/raw or any other folder under SD card. We are going to refer the audio file based on the Uri.
  • Create MediaPlayer object:
    	
    MediaPlayer mPlayer new MediaPlayer();
  • Locate the audio file:
    Uri myUri1 = Uri.parse("file:///sdcard/Songs/ARR Hits/hosannatamil.mp3");
  • Set the audio stream type of the media player:
    	
    mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
  • Set the data source as a content Uri:
    	
    try {
    mPlayer.setDataSource(getApplicationContext(), myUri1);
    } catch (IllegalArgumentException e) {
    Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
    } catch (SecurityException e) {
    Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
    } catch (IllegalStateException e) {
    Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
    } catch (IOException e) {
    e.printStackTrace();
    }
  • Prepare the player for playback, synchronously:
    	
    try {
    mPlayer.prepare();
    } catch (IllegalStateException e) {
    Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
    } catch (IOException e) {
    Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
    }
  • Start the player:
    	
    mPlayer.start();

That’s it. Let us create a sample application to demonstrate the usage of MediaPlayer to access local resource(Music file) present in the system/device and play it.

Create objects for Media player and buttons right under the MusicAndroidActivity class

	
MediaPlayer mPlayer;
Button buttonPlay;
Button buttonStop;

Write listeners for the two buttons we created

Add below code snippets inside onCreate() method so that once the activity is launched, it will listen for button click events.

Button click event listener to play music:

		buttonPlay = (Button) findViewById(R.id.play);
		buttonPlay.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// Even you can refer resource in res/raw directory
				//Uri myUri = Uri.parse("android.resource://com.prgguru.example/" + R.raw.hosannatamil); 
				Uri myUri1 = Uri.parse("file:///sdcard/Songs/ARR Hits/hosannatamil.mp3");
				mPlayer = new MediaPlayer();
				mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
				try {
					mPlayer.setDataSource(getApplicationContext(), myUri1);
				} catch (IllegalArgumentException e) {
					Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
				} catch (SecurityException e) {
					Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
				} catch (IllegalStateException e) {
					Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
				} catch (IOException e) {
					e.printStackTrace();
				}
				try {
					mPlayer.prepare();
				} catch (IllegalStateException e) {
					Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
				} catch (IOException e) {
					Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
				}
				mPlayer.start();
			}
		});

Button click event listener to stop music:

		buttonStop = (Button) findViewById(R.id.stop);
		buttonStop.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(mPlayer!=null && mPlayer.isPlaying()){
					mPlayer.stop();
				}
			}
		});

We are done with the coding part, let us test the application.

[pglinkadssmall1]

Demo

Let us test the application:
Run click on the project >> Run as >> Android application
You could see following screens:




Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project(How to import android project in eclipse). If you just want to run the application in your mobile and see the output but don’t want to hit your head with source code, download application(apk) file and install it in your mobile device.

Download Source Code Download Application(apk)

*apk in Android is the installation file simliar to exe in windows.

[pglinkadssmall]

I hope you enjoyed the post!! :). Do share your comments right away from the comment box below.
[pgfeedback]
[pgwriteforus]

Related Articles

Author: Udhay

Share This Post On
468 ad
  • pvs kalyan

    nice post..thank you..

  • Prakash

    Nice post.
    The coding is to play the media file from SD card and for single MP3 file. Pls post the tutorial to play the multiple songs that located in SD card & Internal device memory.

    • Sure we will write post on playing multiple songs that located in SD card.

      • Prakash

        I tried ur code and try to install .apk file into my device. But my device showing the error message “Unfortunately, Package intaller has Stopped” while installing the .apk file.
        I cannot able to check the app whether working or not.

        • Can you debug the application in your mobile device?

Join now to get more access to our Android Tutorials

Join now to get more access to our Android Tutorials

Once you Join, you will receive Mail containing latest Android Tutorials once a month !!

I promise I wont spam you !!

You have Successfully Subscribed!

Pin It on Pinterest

Shares