Simple Android mp3 media player example

Published by Igor Khrupin on

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:

<?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();
        }
    }
}
Download it from github

39 Comments

Dominick Balistreri · 26 February, 2011 at 18:44

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

Dominick Balistreri · 26 February, 2011 at 20:00

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();
}
}
}

Igor · 27 February, 2011 at 12:11

Hi, Dominick Balistreri.
Thanks for your comment.
I just made some source code updates. Please, look it. It must helps you

Krishna · 24 July, 2011 at 08:10

Thanks for writing this tutorial… It is really helpful..
Thanks again

Alejandro · 16 August, 2011 at 10:13

This was a great help, thank you for your effort.

shrenik · 21 November, 2011 at 13:05

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

wos · 23 December, 2011 at 17:59

sip… trimakasih banyak untuk demo projeknya..

Ishaq · 19 January, 2012 at 15:19

Thanks, I really find this very usefull.

gokul · 17 February, 2012 at 10:22

Thanks a lot. I am using this. Its very help full

Iram · 16 March, 2012 at 18:36

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 🙂

    muzamal · 2 March, 2018 at 13:13

    very simple just add ondestroy or onbackpressed you add mp.stop(); mp.released();

Slavi · 20 March, 2012 at 08:27

Hi,

thanks for the example & download code!

Fajr · 7 April, 2012 at 18:38

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 😀

JackLampro · 16 May, 2012 at 07:49

Thanks for your source code.

JackLampro · 16 May, 2012 at 11:33

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 ??

JackLampro · 16 May, 2012 at 11:35

*SDK 14

toto · 23 May, 2012 at 07:10

thank you very much for sharing this simple mp3 player.
This is very help for me 🙂

ADS · 23 May, 2012 at 14:25

DFGD

SivaKumarK · 29 May, 2012 at 22:24

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

SivaKumarK · 29 May, 2012 at 22:28

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

Franklin DN · 1 June, 2012 at 03:33

That is great!
Thank a lot Igor!

umesh · 9 June, 2012 at 13:59

Thanks Dear for this tutorial.

Fra · 14 June, 2012 at 15:25

Hi, very useful tutorial.

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

kimonas · 8 July, 2012 at 14:23

thanx you.. Very helpful..!!!

Dr.jacky · 9 July, 2012 at 08:06

hi, its play even i push back button!
how solve it?!

dilip · 6 August, 2012 at 14:41

thanks this code helpful great

Samir · 13 August, 2012 at 14:32

Just simple and useful… helped me in completing my app…
Thanks for the post

sajjad · 3 January, 2014 at 11:59

bro from where it will get music files?

Igor Khrupin · 3 January, 2014 at 17:53

Hi @sajjad,

The music file located in the `raw` recourse dir. Here is link from github https://github.com/ihrupin/samples/blob/master/android/Mp3_Player/res/raw/testsong_20_sec.mp3

zia · 9 August, 2014 at 16:47

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.

abdul · 23 September, 2014 at 08:02

hi, this work fine thanks for the tutorial can i show the lyrics of the song as audio plays..
please help me with this ploblem..

    Igor Khrupin · 23 September, 2014 at 17:00

    Hi Abdul,

    You can do it if your server api support this functionality. You unable to get lyrics from audio file in runtime using Android SDK. Correct me please if you know doe feature for it.

Navid · 23 November, 2014 at 08:32

thanks for the nice code, it works perfectly

Kemal Can ÖZÇELÄ°K · 6 May, 2016 at 21:26

That was good one… Thanks dude..

askary · 6 December, 2016 at 07:18

Thank you dude :* :* :* :*

Mass Mathesh · 20 January, 2017 at 19:54

how to solve “cannot resolve symbol R”

    Brandon · 7 December, 2017 at 15:39

    You simply have to import your .R file into the view.

SYED IMTHIYAAS · 23 March, 2018 at 20:01

It shows error on the line
mPlayer = MediaPlayer.create(this, R.raw.somemusicfile);

    Anouar Hakim · 24 April, 2018 at 15:27

    Hello
    to resolve this problem :
    you want to create a “Directory” in “res” folder and give a name “raw”
    ——> after copying your file “mp3” in the folder “raw” and renamed for example: Bella.mp3
    —–> so the code has become like this:
    mPlayer = MediaPlayer.create (this, R.raw.bella);

Leave a Reply to SivaKumarK Cancel reply

Avatar placeholder

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

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