Android Mediaplayer Example – Play from local resource

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) [Similar to Button Listener – Make the cat start Meowing]
  2. Standalone files in the filesystem [Android Mediaplayer Example – Play from URI]
  3. Data stream arriving over a network connection [Android Mediaplayer Example – Play from Internet]


Here we will discuss about how we can play application’s music files (normally music files are placed under res/raw directory).

[pgsubscribe]

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 MusicAndroidActivity1
  • 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 from local Resource(Application)"
        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 raw resource inside a application

  • Place music files(s) under res/raw folder (from where Android will pick the media resources)
  • Create MediaPlayer object with the local raw resource.
    	
    MediaPlayer mPlayer;
    MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.music_file);
  • Play the media player you just created by invoking start() method:
    mediaPlayer.start();

That’s it. Let us create a sample application to demonstrate the usage of MediaPlayer to access local resource(Music file) 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) {
				// TODO Auto-generated method stub
				mPlayer = MediaPlayer.create(getApplicationContext(),R.raw.hosannahindi);//Create MediaPlayer object with MP3 file under res/raw folder
				mPlayer.start();//Start playing the music
			}
		});

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()){//If music is playing already
					mPlayer.stop();//Stop playing the music
				}
			}
		});

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
  • Risal Panimba

    this is great tutorial..
    know, i’ve been make a game in eclipse..
    every game’s also have sound setting,,
    and my game have 2 sound setting, one for background sound and other one for Button Sound when it’s click.
    my logical is when the sound button i click it’s must be silent button.. but i can’t make it..
    please help me,, i don’t know to use it..
    thank”s before…

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