Simple Android mp3 media player example

Here i want to write about my first experience in Android Dev.
This application just play embedded in application mp3 file. That’s all.
Below you can download the source code.
In first step i create a simple Android UI. Below you can see this:

The source text (main.xml) of this UI is:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/widget31"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
    <Button
        android:text="@string/play_str"
        android:textSize="15pt"
        android:textStyle="bold"
        android:id="@+id/ButtonPlayStop"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
    <SeekBar
        android:id="@+id/SeekBar01"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:layout_below="@id/ButtonPlayStop"/>
</RelativeLayout>

In my simple mp3 media player i have few string constans, like “PLAY”, “PAUSE”, etc. The best practice is place this constats in special part of project. That part call values. In this part i Eclipse create for me strings.xml file and change it. Bellow you can see strings.xml content:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Android mp3 player</string>
    <string name="play_str">PLAY</string>
    <string name="pause_str">PAUSE</string>
</resources>

It’s very simple and useful practice.

Next i make changes in Activity file (Mp3player.java). Bellow i give you some comments about it:

package com.hrupin.mp3player;

import com.hrupin.mp3player.R;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.SeekBar;

public class Mp3player extends Activity {

    private Button buttonPlayStop;
    private MediaPlayer mediaPlayer;
    private SeekBar seekBar;

    private final Handler handler = new Handler();

    // Here i override onCreate method.
    //
    // setContentView() method set the layout that you will see then
    // the application will starts
    //
    // initViews() method i create to init views components.
    @Override
    public void onCreate(Bundle icicle) {
            super.onCreate(icicle);
            setContentView(R.layout.main);
            initViews();  

    }

    // This method set the setOnClickListener and method for it (buttonClick())
    private void initViews() {
        buttonPlayStop = (Button) findViewById(R.id.ButtonPlayStop);
        buttonPlayStop.setOnClickListener(new OnClickListener() {@Override public void onClick(View v) {buttonClick();}});

        mediaPlayer = MediaPlayer.create(this, R.raw.testsong_20_sec); 

        seekBar = (SeekBar) findViewById(R.id.SeekBar01);
        seekBar.setMax(mediaPlayer.getDuration());
        seekBar.setOnTouchListener(new OnTouchListener() {@Override public boolean onTouch(View v, MotionEvent event) {
        	seekChange(v);
			return false; }
		});

    }

    public void startPlayProgressUpdater() {
    	seekBar.setProgress(mediaPlayer.getCurrentPosition());

		if (mediaPlayer.isPlaying()) {
			Runnable notification = new Runnable() {
		        public void run() {
		        	startPlayProgressUpdater();
				}
		    };
		    handler.postDelayed(notification,1000);
    	}else{
    		mediaPlayer.pause();
    		buttonPlayStop.setText(getString(R.string.play_str));
    		seekBar.setProgress(0);
    	}
    } 

    // This is event handler thumb moving event
    private void seekChange(View v){
    	if(mediaPlayer.isPlaying()){
	    	SeekBar sb = (SeekBar)v;
			mediaPlayer.seekTo(sb.getProgress());
		}
    }

    // This is event handler for buttonClick event
    private void buttonClick(){
        if (buttonPlayStop.getText() == getString(R.string.play_str)) {
            buttonPlayStop.setText(getString(R.string.pause_str));
            try{
            	mediaPlayer.start();
                startPlayProgressUpdater();
            }catch (IllegalStateException e) {
            	mediaPlayer.pause();
            }
        }else {
            buttonPlayStop.setText(getString(R.string.play_str));
            mediaPlayer.pause();
        }
    }
}

That’s all. It’s simple example, i hope it was interesting for you :)
Download the source .Click here to download full Android project’s source code

29 thoughts on “Simple Android mp3 media player example

  1. Hi..

    Thank you so much for the tutorial on the media player..
    Unlike some other tutorials, it worked perfectly right away and I learned quite a bit from it, so thank you again.

    I wanted to know if you could help me get the “SEEKBAR” to follow the position of the song as it plays.

    Since, I’m new to Android and java, I’m still having some trouble getting my arms around the big picture.

    Thank you again,

    Nick

  2. Hi again,

    Below is my source code. I pretty much just changed a couple of small things from your example above. However, the seekbar doesn’t follow the music.

    Any ideas as to what I’m doing wrong ???

    // beginning my code

    package com.dt.player.one;

    import android.app.Activity;
    import android.media.MediaPlayer;
    import android.os.Bundle;
    import android.os.Handler;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.SeekBar;
    import android.widget.SeekBar.OnSeekBarChangeListener;

    public class dtMenu extends Activity {
    private Button buttonPlayStop;
    private MediaPlayer mPlayer;
    private SeekBar seekBar;

    private final Handler handler = new Handler();

    // Here i override onCreate method.
    //
    // setContentView() method set the layout that you will see then
    // the application will starts
    //

    @Override
    public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    initViews();
    }

    // This method set the setOnClickListener and method for it (buttonClick())
    private void initViews() {
    buttonPlayStop = (Button) findViewById(R.id.ButtonPlayStop);
    buttonPlayStop.setOnClickListener(new OnClickListener()
    {public void onClick(View v) {buttonClick();}});

    mPlayer = MediaPlayer.create(this, R.raw.sqeefoot);

    seekBar = (SeekBar) findViewById(R.id.SeekBar01);
    seekBar.setMax(mPlayer.getDuration());

    seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

    public void onStopTrackingTouch(SeekBar seekBar) {
    // TODO Auto-generated method stub
    }

    public void onStartTrackingTouch(SeekBar seekBar) {
    // TODO Auto-generated method stub
    }

    public void onProgressChanged(SeekBar seekBar, int progress,
    boolean fromUser) {
    seekChange(seekBar, progress, fromUser);

    }
    });
    }

    // This makes the seekbar follow the music
    public void startPlayProgressUpdater() {
    seekBar.setProgress(mPlayer.getCurrentPosition());

    if (mPlayer.isPlaying()) {
    Runnable notification = new Runnable() {
    public void run() {
    startPlayProgressUpdater();
    }
    };
    handler.postDelayed(notification,1000);
    }else{
    mPlayer.pause();
    buttonPlayStop.setText(getString(R.string.play_str));
    seekBar.setProgress(0);
    }
    }

    // This is event handler thumb moving event
    private void seekChange(SeekBar seekBar, int progress,
    boolean fromUser){
    mPlayer.seekTo(progress);
    }

    // This is event handler for buttonClick event
    private void buttonClick(){
    if (buttonPlayStop.getText() == getString(R.string.play_str)) {
    buttonPlayStop.setText(getString(R.string.pause_str));
    try{
    mPlayer.start();
    }catch (IllegalStateException e) {
    mPlayer.pause();
    }
    }else {
    buttonPlayStop.setText(getString(R.string.play_str));
    mPlayer.pause();
    }
    }
    }

  3. hi Dominick Balistreri
    I copied your program. Its working but seek bar doesn’t synchronize with the song. please publish the solution for that.

  4. it ws gud n simple example for trying out media player example.
    howevr ders a simple prb in d app…..dat is whn user returns back to d app…he is able to play d song again …which leads to same media file playing more den one time in background….and dat should not happen!
    so to overcome dis prb u jst need to make a simple chng in your androidManifest file within tag set android:launchMode=”singleTask”
    thnx keep posting :)

  5. Thx for the code. i really need this for my project.
    in this code

    seekBar.setProgress(0);

    i think it means that every time buttonPLayStop click to pause the progress will be default to the start again, So how to make the progress bar always update every second the music pause. I really apreciate that thx, sorry my english was really bad :D

  6. hi admin,
    i have used your code, but i configurated SDK 4 and android 4.0 and i happend some problem:

    ActivityThread.performLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 1573
    can you help ??

  7. Thanks for your code…………will u plz give me the code for asking a password before the call came

  8. I have a good idea,but to implement that i want the above code….so plz help me….Is it possible to access only the games not any other applicaion within our application

  9. Hi, very useful tutorial.

    I was wondering, how to implement something like the seek bar to control the volume?

  10. I am using code for android version 4.4.2 and API 19 , after using the code clicking PLAY nothing happens.
    Could you please help me.

Leave a Reply

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


one + 8 =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>