You are on page 1of 46

13/8/2015

AndroidBuildingAudioPlayerTutorial

Android Building Audio Player Tutorial


563 Comments . By Ravi Tamada . on March 5, 2012

In this tutorial i am going to discuss building a simple


audio player with basic controls like play, pause,
forward, backward, next, previous, playlist and seekbar.
This app basically will read all audio files(.mp3) from
sdcard and plays selected song. For this tutorial i am
referencing MediaPlayer and go through it if you need
any documentation about usage.

AdvertiseHere

http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

1/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

Android Building Audio Player Tutorial (Demo)

Android MediaPlayer Class


Android SDK is providing MediaPlayer Class to access android in built mediaplayer services like playing
audio, video etc., In this tutorial i am using following functions of this class to control audio player.

MediaPlayermp=newMediaPlayer();

//Setdatasource
setDataSource("/sdcard/path_to_song");

//Playaudio
mp.start();

//Pauseaudio
mp.pause();

//Resetmediaplayer
mp.reset();

//Getsonglengthdurationinmilliseconds
mp.getDuration();

//Getcurrentdurationinmilliseconds
mp.getCurrentDuration();

//MovesongtoparticularsecondusedforForwardorBackward
mp.seekTo(positon);//positioninmilliseconds

http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

2/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

//Checkifsongisplayingornot
mp.isPlaying();//returnstrueorfalse

1. Designing the Audio Player Layout


Design your audio player using some graphic designing softwares like photoshop. I used photoshop to
design this app layout. If you are not aware of designing just download the required images from the
internet. Following is a screenshot of the audio player which we are going to build in this tutorial. (You
can find this layout PSD in the download code)

2. Preparing Required Icons and Images


Once you are done with your app layout design, prepare the required icons and background images
for the audio player application. Prepare your icons in different states like default, focused and
pressed and place them all in your drawable folder.
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

3/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

4/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

3. Writing XML layouts for ICON states (default/hover/pressed)


After saving all the icons with different states, we need to write xml drawable for each icon. Following
is a sample for play button. Save this file under drawable folder.

BTN_PLAY.XML

<selectorxmlns:android="http://schemas.android.com/apk/res/android">
<itemandroid:drawable="@drawable/img_btn_play_pressed"
android:state_focused="true"
android:state_pressed="true"/>
<itemandroid:drawable="@drawable/img_btn_play_pressed"
android:state_focused="false"
android:state_pressed="true"/>
<itemandroid:drawable="@drawable/img_btn_play_pressed"
android:state_focused="true"/>
<itemandroid:drawable="@drawable/img_btn_play"
android:state_focused="false"
android:state_pressed="false"/>
</selector>
Note: You need to write xml drawable for each icon you used for the player (like btn_pause.xml,
btn_next.xml etc,.)

4. Writing XML design for SeekBar


In this tutorial i used customized SeekBar to show song progress. You can design the style of default
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

5/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

SeekBar using xml styles. In your drawable folder create to xml files and type the following code.
Changing SeekBar background:

SEEKBAR_PROGRESS_BG.XML

<?xmlversion="1.0"encoding="utf8"?>
<layerlistxmlns:android="http://schemas.android.com/apk/res/android">
<item>
<clip>
<bitmapxmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/img_seekbar_progress_blue"
android:tileMode="repeat"
android:antialias="true"
android:dither="false"
android:filter="false"
android:gravity="left"
/>
</clip>
</item>
</layerlist>
Changing SeekBar Progress:

SEEKBAR_PROGRESS.XML

<?xmlversion="1.0"encoding="utf8"?>
<layerlistxmlns:android="http://schemas.android.com/apk/res/android">
<itemandroid:id="@android:id/background"
android:drawable="@drawable/img_seekbar_bg"
android:dither="true">
</item>
<itemandroid:id="@android:id/secondaryProgress">
<clip>
<shape>
<gradient
android:startColor="#80028ac8"
android:centerColor="#80127fb1"
android:centerY="0.75"
android:endColor="#a004638f"
android:angle="270"
/>
</shape>
</clip>
</item>
<item
android:id="@android:id/progress"
android:drawable="@drawable/seekbar_progress_bg"
/>
</layerlist>
Actual seekbar which uses above xml files:
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

6/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

<SeekBar
android:id="@+id/songProgressBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:layout_marginBottom="20dp"
android:layout_above="@id/player_footer_bg"
android:thumb="@drawable/seek_handler"
android:progressDrawable="@drawable/seekbar_progress"
android:paddingLeft="6dp"
android:paddingRight="6dp"/>

5. Writing XML for Player Layout


So far we created separate xml layout for all the icons, seekbar. Now we need to combine everything
into single layout. Create a new file called player.xml under layout folder and paste the following
code.

PLAYER.XML

<?xmlversion="1.0"encoding="utf8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/player_background">

<!PlayerHeader>
<LinearLayout
android:id="@+id/player_header_bg"
android:layout_width="fill_parent"
android:layout_height="60dip"
android:background="@layout/bg_player_header"
android:layout_alignParentTop="true"
android:paddingLeft="5dp"
android:paddingRight="5dp">

<!SongTitle>
<TextView
android:id="@+id/songTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#04b3d2"
android:textSize="16dp"
android:paddingLeft="10dp"
android:textStyle="bold"
android:text="TheGood,TheBadAndTheUgly"
android:layout_marginTop="10dp"/>

<!Playlistbutton>
<ImageButton
android:id="@+id/btnPlaylist"
android:layout_width="wrap_content"
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

7/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

android:layout_height="fill_parent"
android:src="@drawable/btn_playlist"
android:background="@null"/>
</LinearLayout>

<!SongThumbnailImage>
<LinearLayout
android:id="@+id/songThumbnail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:gravity="center"
android:layout_below="@id/player_header_bg">
<ImageViewandroid:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/adele"/>
</LinearLayout>

<!PlayerFooter>
<LinearLayout
android:id="@+id/player_footer_bg"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:background="@layout/bg_player_footer"
android:gravity="center">

<!PlayerButtons>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:background="@layout/rounded_corner"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<!PreviousButton>
<ImageButton
android:id="@+id/btnPrevious"
android:src="@drawable/btn_previous"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@null"/>
<!BackwardButton>
<ImageButton
android:id="@+id/btnBackward"
android:src="@drawable/btn_backward"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@null"/>
<!PlayButton>
<ImageButton
android:id="@+id/btnPlay"
android:src="@drawable/btn_play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@null"/>
<!ForwardButton>
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

8/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

<ImageButton
android:id="@+id/btnForward"
android:src="@drawable/btn_forward"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@null"/>
<!NextButton>
<ImageButton
android:id="@+id/btnNext"
android:src="@drawable/btn_next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@null"/>
</LinearLayout>
</LinearLayout>

<!ProgressBar/Seekbar>
<SeekBar
android:id="@+id/songProgressBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:layout_marginBottom="20dp"
android:layout_above="@id/player_footer_bg"
android:thumb="@drawable/seek_handler"
android:progressDrawable="@drawable/seekbar_progress"
android:paddingLeft="6dp"
android:paddingRight="6dp"/>

<!TimerDisplay>
<LinearLayout
android:id="@+id/timerDisplay"
android:layout_above="@id/songProgressBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:layout_marginBottom="10dp">
<!CurrentDurationLabel>
<TextView
android:id="@+id/songCurrentDurationLabel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:textColor="#eeeeee"
android:textStyle="bold"/>
<!TotalDurationLabel>
<TextView
android:id="@+id/songTotalDurationLabel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="right"
android:textColor="#04cbde"
android:textStyle="bold"/>
</LinearLayout>

http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

9/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

<!Repeat/Shufflebuttons>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="@id/timerDisplay"
android:gravity="center">
<!RepeatButton>
<ImageButton
android:id="@+id/btnRepeat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/btn_repeat"
android:layout_marginRight="5dp"
android:background="@null"/>

<!ShuffleButton>
<ImageButton
android:id="@+id/btnShuffle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/btn_shuffle"
android:layout_marginLeft="5dp"
android:background="@null"/>
</LinearLayout>
</RelativeLayout>
The above xml will give following output layout.

http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

10/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

6. Writing XML for PlayList ListView


Playlist is displayed using a listview. If you are not aware of listview go through this Android ListView
Tutorial and get an idea of listview layout.
Create an xml file under drawable folder and name it as list_selector.xml and type following code.
This xml is used for gradient background for list item.

http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

11/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

LIST_SELECTOR.XML

<?xmlversion="1.0"encoding="utf8"?>
<selectorxmlns:android="http://schemas.android.com/apk/res/android">
<!Selectorstyleforlistrow>
<item
android:state_selected="false"
android:state_pressed="false"
android:drawable="@drawable/gradient_bg"/>
<itemandroid:state_pressed="true"
android:drawable="@drawable/gradient_bg_hover"/>
<itemandroid:state_selected="true"
android:state_pressed="false"
android:drawable="@drawable/gradient_bg_hover"/>
</selector>
Create a new xml file under layout layout folder and name it as playlist.xml and type the following
code. This xml file is for listview.

PLAYLIST.XML

<?xmlversion="1.0"encoding="utf8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">

<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="#242424"
android:dividerHeight="1dp"
android:listSelector="@drawable/list_selector"/>

</LinearLayout>
Also create a new xml file under layout folder for single List Item. Name file as playlist_item.xml
and type following code. This xml file is for single list item which holds song title.

PLAYLIST_ITEM.XML

<?xmlversion="1.0"encoding="utf8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:background="@drawable/list_selector"
android:padding="5dp">
<TextView
android:id="@+id/songTitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

12/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

android:textSize="16dp"
android:padding="10dp"
android:color="#f3f3f3"/>
</LinearLayout>
By using above layout we can achieve following list view by loading data into it.

7. Writing Class for reading MP3 files from SDcard


So far we are done with static layouts for the player. Now the actual code starts.
Create a new class file and name it as SongsManager.java. This class will read all the files from device
sdcard and filters the files which are having .mp3 extension.

SONGSMANAGER.MP3
packagecom.androidhive.musicplayer;
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

13/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

importjava.io.File;
importjava.io.FilenameFilter;
importjava.util.ArrayList;
importjava.util.HashMap;

publicclassSongsManager{
//SDCardPath
finalStringMEDIA_PATH=newString("/sdcard/");
privateArrayList<HashMap<String,String>>songsList=newArrayList<HashMap<String,

//Constructor
publicSongsManager(){

/**
*Functiontoreadallmp3filesfromsdcard
*andstorethedetailsinArrayList
**/
publicArrayList<HashMap<String,String>>getPlayList(){
Filehome=newFile(MEDIA_PATH);

if(home.listFiles(newFileExtensionFilter()).length>0){
for(Filefile:home.listFiles(newFileExtensionFilter())){
HashMap<String,String>song=newHashMap<String,String>();
song.put("songTitle",file.getName().substring(0,(file.getName().length
song.put("songPath",file.getPath());

//AddingeachsongtoSongList
songsList.add(song);
}
}
//returnsongslistarray
returnsongsList;
}

/**
*Classtofilterfileswhicharehaving.mp3extension
**/
classFileExtensionFilterimplementsFilenameFilter{
publicbooleanaccept(Filedir,Stringname){
return(name.endsWith(".mp3")||name.endsWith(".MP3"));
}
}
}

8. Writing Class for PlayList ListView


Create a new Activity class for playlist listview. Name the file as PlayListActivity.java This class will
display list of songs in list layout by using SongsManager.java class

PLAYLISTACTIVITY.JAVA
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

14/46

13/8/2015

PLAYLISTACTIVITY.JAVA

AndroidBuildingAudioPlayerTutorial

packagecom.androidhive.musicplayer;

importjava.util.ArrayList;
importjava.util.HashMap;

importandroid.app.ListActivity;
importandroid.content.Intent;
importandroid.os.Bundle;
importandroid.view.View;
importandroid.widget.AdapterView;
importandroid.widget.AdapterView.OnItemClickListener;
importandroid.widget.ListAdapter;
importandroid.widget.ListView;
importandroid.widget.SimpleAdapter;

publicclassPlayListActivityextendsListActivity{
//Songslist
publicArrayList<HashMap<String,String>>songsList=newArrayList<HashMap<String,

@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.playlist);

ArrayList<HashMap<String,String>>songsListData=newArrayList<HashMap<String,

SongsManagerplm=newSongsManager();
//getallsongsfromsdcard
this.songsList=plm.getPlayList();

//loopingthroughplaylist
for(inti=0;i<songsList.size();i++){
//creatingnewHashMap
HashMap<String,String>song=songsList.get(i);

//addingHashListtoArrayList
songsListData.add(song);
}

//AddingmenuItemstoListView
ListAdapteradapter=newSimpleAdapter(this,songsListData,
R.layout.playlist_item,newString[]{"songTitle"},newint[]{
R.id.songTitle});

setListAdapter(adapter);

//selectingsingleListViewitem
ListViewlv=getListView();
//listeningtosinglelistitemclick
lv.setOnItemClickListener(newOnItemClickListener(){

@Override
publicvoidonItemClick(AdapterView<?>parent,Viewview,
intposition,longid){
//gettinglistitemindex
intsongIndex=position;

//Startingnewintent
Intentin=newIntent(getApplicationContext(),
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

15/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

AndroidBuildingMusicPlayerActivity.class);
//SendingsongIndextoPlayerActivity
in.putExtra("songIndex",songIndex);
setResult(100,in);
//ClosingPlayListView
finish();
}
});
}
}

9. Helper Class functions


Create a new class called Utilities.java for handling extra work like converting time to progress
percentage and vice-versa. Also it has function to convert millisecond to a timer string which will
displayed on the seekbar of the player.

UTILITIES.JAVA
packagecom.androidhive.musicplayer;

publicclassUtilities{

/**
*Functiontoconvertmillisecondstimeto
*TimerFormat
*Hours:Minutes:Seconds
**/
publicStringmilliSecondsToTimer(longmilliseconds){
StringfinalTimerString="";
StringsecondsString="";

//Converttotaldurationintotime
inthours=(int)(milliseconds/(1000*60*60));
intminutes=(int)(milliseconds%(1000*60*60))/(1000*60);
intseconds=(int)((milliseconds%(1000*60*60))%(1000*60)/1000);
//Addhoursifthere
if(hours>0){
finalTimerString=hours+":";
}

//Prepending0tosecondsifitisonedigit
if(seconds<10){
secondsString="0"+seconds;
}else{
secondsString=""+seconds;}

finalTimerString=finalTimerString+minutes+":"+secondsString;

//returntimerstring
returnfinalTimerString;
}

http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

16/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

/**
*FunctiontogetProgresspercentage
*@paramcurrentDuration
*@paramtotalDuration
**/
publicintgetProgressPercentage(longcurrentDuration,longtotalDuration){
Doublepercentage=(double)0;

longcurrentSeconds=(int)(currentDuration/1000);
longtotalSeconds=(int)(totalDuration/1000);

//calculatingpercentage
percentage=(((double)currentSeconds)/totalSeconds)*100;

//returnpercentage
returnpercentage.intValue();
}

/**
*Functiontochangeprogresstotimer
*@paramprogress
*@paramtotalDuration
*returnscurrentdurationinmilliseconds
**/
publicintprogressToTimer(intprogress,inttotalDuration){
intcurrentDuration=0;
totalDuration=(int)(totalDuration/1000);
currentDuration=(int)((((double)progress)/100)*totalDuration);

//returncurrentdurationinmilliseconds
returncurrentDuration*1000;
}
}

7. Writing Classes needed for Audio Player


Open your main activity class which deals with main player interface and make the class implements
from OnCompletionListener, SeekBar.OnSeekBarChangeListener.
In this case my main activity name is AndroidBuildingMusicPlayerActivity.

ANDROIDBUILDINGMUSICPLAYERACTIVITY.JAVA
publicclassAndroidBuildingMusicPlayerActivityextendsActivity
implementsOnCompletionListener,SeekBar.OnSeekBarChangeListener{
Now declare all variable needed for this audio player class.

ANDROIDBUILDINGMUSICPLAYERACTIVITY.JAVA
publicclassAndroidBuildingMusicPlayerActivityextendsActivity
implementsOnCompletionListener,SeekBar.OnSeekBarChangeListener{
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

17/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

privateImageButtonbtnPlay;
privateImageButtonbtnForward;
privateImageButtonbtnBackward;
privateImageButtonbtnNext;
privateImageButtonbtnPrevious;
privateImageButtonbtnPlaylist;
privateImageButtonbtnRepeat;
privateImageButtonbtnShuffle;
privateSeekBarsongProgressBar;
privateTextViewsongTitleLabel;
privateTextViewsongCurrentDurationLabel;
privateTextViewsongTotalDurationLabel;
//MediaPlayer
privateMediaPlayermp;
//HandlertoupdateUItimer,progressbaretc,.
privateHandlermHandler=newHandler();;
privateSongsManagersongManager;
privateUtilitiesutils;
privateintseekForwardTime=5000;//5000milliseconds
privateintseekBackwardTime=5000;//5000milliseconds
privateintcurrentSongIndex=0;
privatebooleanisShuffle=false;
privatebooleanisRepeat=false;
privateArrayList<HashMap<String,String>>songsList=newArrayList<HashMap<String,

Now reference all buttons, images from xml layout to class.

ANDROIDBUILDINGMUSICPLAYERACTIVITY.JAVA

//Allplayerbuttons
btnPlay=(ImageButton)findViewById(R.id.btnPlay);
btnForward=(ImageButton)findViewById(R.id.btnForward);
btnBackward=(ImageButton)findViewById(R.id.btnBackward);
btnNext=(ImageButton)findViewById(R.id.btnNext);
btnPrevious=(ImageButton)findViewById(R.id.btnPrevious);
btnPlaylist=(ImageButton)findViewById(R.id.btnPlaylist);
btnRepeat=(ImageButton)findViewById(R.id.btnRepeat);
btnShuffle=(ImageButton)findViewById(R.id.btnShuffle);
songProgressBar=(SeekBar)findViewById(R.id.songProgressBar);
songTitleLabel=(TextView)findViewById(R.id.songTitle);
songCurrentDurationLabel=(TextView)findViewById(R.id.songCurrentDurationLabel
songTotalDurationLabel=(TextView)findViewById(R.id.songTotalDurationLabel);

//Mediaplayer
mp=newMediaPlayer();
songManager=newSongsManager();
utils=newUtilities();

//Listeners
songProgressBar.setOnSeekBarChangeListener(this);//Important
mp.setOnCompletionListener(this);//Important

//Gettingallsongslist
songsList=songManager.getPlayList();
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

18/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

Launching PlayList
Write click event listener to playlist button. On clicking playlist button we need to launch
PlayListAcitivity.java and from listview on selecting a particular song we need get songIndex.

ANDROIDBUILDINGMUSICPLAYERACTIVITY.JAVA
/**
*ButtonClickeventforPlaylistclickevent
*Launcheslistactivitywhichdisplayslistofsongs
**/
btnPlaylist.setOnClickListener(newView.OnClickListener(){

@Override
publicvoidonClick(Viewarg0){
Intenti=newIntent(getApplicationContext(),PlayListActivity.class
startActivityForResult(i,100);
}
});

To receive the selected songIndex add following fucntion. (Make sure that you added this function
outside of onCreate method)

ANDROIDBUILDINGMUSICPLAYERACTIVITY.JAVA
/**
*Receivingsongindexfromplaylistview
*andplaythesong
**/
@Override
protectedvoidonActivityResult(intrequestCode,
intresultCode,Intentdata){
super.onActivityResult(requestCode,resultCode,data);
if(resultCode==100){
currentSongIndex=data.getExtras().getInt("songIndex");
//playselectedsong
playSong(currentSongIndex);
}

Playing Song
Add the following function to your class. This function accepts songIndex as param and plays it. Also
when start playing a song it switches the play button to pause button state.

http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

19/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

ANDROIDBUILDINGMUSICPLAYERACTIVITY.JAVA

/**
*Functiontoplayasong
*@paramsongIndexindexofsong
**/
publicvoidplaySong(intsongIndex){
//Playsong
try{
mp.reset();
mp.setDataSource(songsList.get(songIndex).get("songPath"));
mp.prepare();
mp.start();
//DisplayingSongtitle
StringsongTitle=songsList.get(songIndex).get("songTitle");
songTitleLabel.setText(songTitle);

//ChangingButtonImagetopauseimage
btnPlay.setImageResource(R.drawable.btn_pause);

//setProgressbarvalues
songProgressBar.setProgress(0);
songProgressBar.setMax(100);

//Updatingprogressbar
updateProgressBar();
}catch(IllegalArgumentExceptione){
e.printStackTrace();
}catch(IllegalStateExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
}

Forward / Backward button click events


Add event listeners to Forward and Backward buttons which forwards or backwards song by specified
seconds.
Forward button click event moves song to specified number of seconds forward

ANDROIDBUILDINGMUSICPLAYERACTIVITY.JAVA
/**
*Forwardbuttonclickevent
*Forwardssongspecifiedseconds
**/
btnForward.setOnClickListener(newView.OnClickListener(){

@Override
publicvoidonClick(Viewarg0){
//getcurrentsongposition
intcurrentPosition=mp.getCurrentPosition();
//checkifseekForwardtimeislesserthansongduration
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

20/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

if(currentPosition+seekForwardTime<=mp.getDuration()){
//forwardsong
mp.seekTo(currentPosition+seekForwardTime);
}else{
//forwardtoendposition
mp.seekTo(mp.getDuration());
}
}
});
Backward button click event moves song to specified number of seconds backward

ANDROIDBUILDINGMUSICPLAYERACTIVITY.JAVA
/**
*Backwardbuttonclickevent
*Backwardsongtospecifiedseconds
**/
btnBackward.setOnClickListener(newView.OnClickListener(){

@Override
publicvoidonClick(Viewarg0){
//getcurrentsongposition
intcurrentPosition=mp.getCurrentPosition();
//checkifseekBackwardtimeisgreaterthan0sec
if(currentPositionseekBackwardTime>=0){
//forwardsong
mp.seekTo(currentPositionseekBackwardTime);
}else{
//backwardtostartingposition
mp.seekTo(0);
}

}
});

Next / Back button click events


Add click listeners to next and back buttons.
Next button click event which plays next song from the playlist if presents else plays first song

ANDROIDBUILDINGMUSICPLAYERACTIVITY.JAVA
/**
*Nextbuttonclickevent
*PlaysnextsongbytakingcurrentSongIndex+1
**/
btnNext.setOnClickListener(newView.OnClickListener(){

@Override
publicvoidonClick(Viewarg0){
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

21/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

//checkifnextsongisthereornot
if(currentSongIndex<(songsList.size()1)){
playSong(currentSongIndex+1);
currentSongIndex=currentSongIndex+1;
}else{
//playfirstsong
playSong(0);
currentSongIndex=0;
}

}
});
Back button click event which plays previous song if presents or plays last song

ANDROIDBUILDINGMUSICPLAYERACTIVITY.JAVA
/**
*Backbuttonclickevent
*PlaysprevioussongbycurrentSongIndex1
**/
btnPrevious.setOnClickListener(newView.OnClickListener(){

@Override
publicvoidonClick(Viewarg0){
if(currentSongIndex>0){
playSong(currentSongIndex1);
currentSongIndex=currentSongIndex1;
}else{
//playlastsong
playSong(songsList.size()1);
currentSongIndex=songsList.size()1;
}

}
});

Updating SeekBar progress and Timer


To update progress bar timer i implemented a background thread which runs in background using a
Handler. If you new to Handler follow this doc. Updating the UI from a Timer

ANDROIDBUILDINGMUSICPLAYERACTIVITY.JAVA
/**
*Updatetimeronseekbar
**/
publicvoidupdateProgressBar(){
mHandler.postDelayed(mUpdateTimeTask,100);
}

/**
*BackgroundRunnablethread
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

22/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

**/
privateRunnablemUpdateTimeTask=newRunnable(){
publicvoidrun(){
longtotalDuration=mp.getDuration();
longcurrentDuration=mp.getCurrentPosition();

//DisplayingTotalDurationtime
songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration
//Displayingtimecompletedplaying
songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDura

//Updatingprogressbar
intprogress=(int)(utils.getProgressPercentage(currentDuration,totalDu
//Log.d("Progress",""+progress);
songProgressBar.setProgress(progress);

//Runningthisthreadafter100milliseconds
mHandler.postDelayed(this,100);
}
};

/**
*
**/
@Override
publicvoidonProgressChanged(SeekBarseekBar,intprogress,booleanfromTouch){

/**
*Whenuserstartsmovingtheprogresshandler
**/
@Override
publicvoidonStartTrackingTouch(SeekBarseekBar){
//removemessageHandlerfromupdatingprogressbar
mHandler.removeCallbacks(mUpdateTimeTask);
}

/**
*Whenuserstopsmovingtheprogresshanlder
**/
@Override
publicvoidonStopTrackingTouch(SeekBarseekBar){
mHandler.removeCallbacks(mUpdateTimeTask);
inttotalDuration=mp.getDuration();
intcurrentPosition=utils.progressToTimer(seekBar.getProgress(),totalDuration

//forwardorbackwardtocertainseconds
mp.seekTo(currentPosition);

//updatetimerprogressagain
updateProgressBar();
}

Repeat button click event


http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

23/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

On clicking repeat button we need to set isRepeat to true and vice-versa. Also we need to change
image source of repeat button to focused state.

ANDROIDBUILDINGMUSICPLAYERACTIVITY.JAVA

/**
*ButtonClickeventforRepeatbutton
*Enablesrepeatflagtotrue
**/
btnRepeat.setOnClickListener(newView.OnClickListener(){

@Override
publicvoidonClick(Viewarg0){
if(isRepeat){
isRepeat=false;
Toast.makeText(getApplicationContext(),"RepeatisOFF",Toast.LENGT
btnRepeat.setImageResource(R.drawable.btn_repeat);
}else{
//makerepeattotrue
isRepeat=true;
Toast.makeText(getApplicationContext(),"RepeatisON",Toast.LENGTH
//makeshuffletofalse
isShuffle=false;
btnRepeat.setImageResource(R.drawable.btn_repeat_focused);
btnShuffle.setImageResource(R.drawable.btn_shuffle);
}
}
});

Shuffle button click event


On clicking shuffle button we need to set isShuffle to true and vice-versa. Also we need to change
image source of shuffle button to focused state.

ANDROIDBUILDINGMUSICPLAYERACTIVITY.JAVA

/**
*ButtonClickeventforShufflebutton
*Enablesshuffleflagtotrue
**/
btnShuffle.setOnClickListener(newView.OnClickListener(){

@Override
publicvoidonClick(Viewarg0){
if(isShuffle){
isShuffle=false;
Toast.makeText(getApplicationContext(),"ShuffleisOFF",Toast.LENG
btnShuffle.setImageResource(R.drawable.btn_shuffle);
}else{
//makerepeattotrue
isShuffle=true;
Toast.makeText(getApplicationContext(),"ShuffleisON",Toast.LENGT
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

24/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

//makeshuffletofalse
isRepeat=false;
btnShuffle.setImageResource(R.drawable.btn_shuffle_focused);
btnRepeat.setImageResource(R.drawable.btn_repeat);
}
}
});

Implementing song onCompletion Listener


It is important to implement this listener which will notify you once the song is completed playing. In
this method we need to play next song automatically depending on repeat and shuffle conditions.

ANDROIDBUILDINGMUSICPLAYERACTIVITY.JAVA
/**
*OnSongPlayingcompleted
*ifrepeatisONplaysamesongagain
*ifshuffleisONplayrandomsong
**/
@Override
publicvoidonCompletion(MediaPlayerarg0){

//checkforrepeatisONorOFF
if(isRepeat){
//repeatisonplaysamesongagain
playSong(currentSongIndex);
}elseif(isShuffle){
//shuffleisonplayarandomsong
Randomrand=newRandom();
currentSongIndex=rand.nextInt((songsList.size()1)0+1)+0;
playSong(currentSongIndex);
}else{
//norepeatorshuffleONplaynextsong
if(currentSongIndex<(songsList.size()1)){
playSong(currentSongIndex+1);
currentSongIndex=currentSongIndex+1;
}else{
//playfirstsong
playSong(0);
currentSongIndex=0;
}
}
}

Update your AndroidManifest.xml


Update

your

AndroidManifest.xml

to

following

code.

Add

android:configChanges=keyboardHidden|orientation to your main activity node.

http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

25/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

ANDROIDMANIFEST.XML
<?xmlversion="1.0"encoding="utf8"?>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidhive.musicplayer"
android:versionCode="1"
android:versionName="1.0">

<usessdkandroid:minSdkVersion="8"/>

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name">
<activity
android:name=".AndroidBuildingMusicPlayerActivity"
android:label="@string/app_name"
android:configChanges="keyboardHidden|orientation">
<intentfilter>
<actionandroid:name="android.intent.action.MAIN"/>

<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intentfilter>
</activity>

<activity
android:name=".PlayListActivity"/>
</application>

</manifest>
<!AndroidBuildingMusicPlayerActivity>

Final Code
Following is complete code for the AndroidBuildingMusicPlayerActivity.java class.

ANDROIDBUILDINGMUSICPLAYERACTIVITY.JAVA
packagecom.androidhive.musicplayer;

importjava.io.IOException;
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.Random;

importandroid.app.Activity;
importandroid.content.Intent;
importandroid.media.MediaPlayer;
importandroid.media.MediaPlayer.OnCompletionListener;
importandroid.os.Bundle;
importandroid.os.Handler;
importandroid.view.View;
importandroid.widget.ImageButton;
importandroid.widget.SeekBar;
importandroid.widget.TextView;
importandroid.widget.Toast;
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

26/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

publicclassAndroidBuildingMusicPlayerActivityextendsActivityimplementsOnCompletion

privateImageButtonbtnPlay;
privateImageButtonbtnForward;
privateImageButtonbtnBackward;
privateImageButtonbtnNext;
privateImageButtonbtnPrevious;
privateImageButtonbtnPlaylist;
privateImageButtonbtnRepeat;
privateImageButtonbtnShuffle;
privateSeekBarsongProgressBar;
privateTextViewsongTitleLabel;
privateTextViewsongCurrentDurationLabel;
privateTextViewsongTotalDurationLabel;
//MediaPlayer
privateMediaPlayermp;
//HandlertoupdateUItimer,progressbaretc,.
privateHandlermHandler=newHandler();;
privateSongsManagersongManager;
privateUtilitiesutils;
privateintseekForwardTime=5000;//5000milliseconds
privateintseekBackwardTime=5000;//5000milliseconds
privateintcurrentSongIndex=0;
privatebooleanisShuffle=false;
privatebooleanisRepeat=false;
privateArrayList<HashMap<String,String>>songsList=newArrayList<HashMap<String,

@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.player);

//Allplayerbuttons
btnPlay=(ImageButton)findViewById(R.id.btnPlay);
btnForward=(ImageButton)findViewById(R.id.btnForward);
btnBackward=(ImageButton)findViewById(R.id.btnBackward);
btnNext=(ImageButton)findViewById(R.id.btnNext);
btnPrevious=(ImageButton)findViewById(R.id.btnPrevious);
btnPlaylist=(ImageButton)findViewById(R.id.btnPlaylist);
btnRepeat=(ImageButton)findViewById(R.id.btnRepeat);
btnShuffle=(ImageButton)findViewById(R.id.btnShuffle);
songProgressBar=(SeekBar)findViewById(R.id.songProgressBar);
songTitleLabel=(TextView)findViewById(R.id.songTitle);
songCurrentDurationLabel=(TextView)findViewById(R.id.songCurrentDurationLabel
songTotalDurationLabel=(TextView)findViewById(R.id.songTotalDurationLabel);

//Mediaplayer
mp=newMediaPlayer();
songManager=newSongsManager();
utils=newUtilities();

//Listeners
songProgressBar.setOnSeekBarChangeListener(this);//Important
mp.setOnCompletionListener(this);//Important

//Gettingallsongslist
songsList=songManager.getPlayList();

http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

27/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

//Bydefaultplayfirstsong
playSong(0);

/**
*Playbuttonclickevent
*playsasongandchangesbuttontopauseimage
*pausesasongandchangesbuttontoplayimage
**/
btnPlay.setOnClickListener(newView.OnClickListener(){

@Override
publicvoidonClick(Viewarg0){
//checkforalreadyplaying
if(mp.isPlaying()){
if(mp!=null){
mp.pause();
//Changingbuttonimagetoplaybutton
btnPlay.setImageResource(R.drawable.btn_play);
}
}else{
//Resumesong
if(mp!=null){
mp.start();
//Changingbuttonimagetopausebutton
btnPlay.setImageResource(R.drawable.btn_pause);
}
}

}
});

/**
*Forwardbuttonclickevent
*Forwardssongspecifiedseconds
**/
btnForward.setOnClickListener(newView.OnClickListener(){

@Override
publicvoidonClick(Viewarg0){
//getcurrentsongposition
intcurrentPosition=mp.getCurrentPosition();
//checkifseekForwardtimeislesserthansongduration
if(currentPosition+seekForwardTime<=mp.getDuration()){
//forwardsong
mp.seekTo(currentPosition+seekForwardTime);
}else{
//forwardtoendposition
mp.seekTo(mp.getDuration());
}
}
});

/**
*Backwardbuttonclickevent
*Backwardsongtospecifiedseconds
**/
btnBackward.setOnClickListener(newView.OnClickListener(){

@Override
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

28/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

publicvoidonClick(Viewarg0){
//getcurrentsongposition
intcurrentPosition=mp.getCurrentPosition();
//checkifseekBackwardtimeisgreaterthan0sec
if(currentPositionseekBackwardTime>=0){
//forwardsong
mp.seekTo(currentPositionseekBackwardTime);
}else{
//backwardtostartingposition
mp.seekTo(0);
}

}
});

/**
*Nextbuttonclickevent
*PlaysnextsongbytakingcurrentSongIndex+1
**/
btnNext.setOnClickListener(newView.OnClickListener(){

@Override
publicvoidonClick(Viewarg0){
//checkifnextsongisthereornot
if(currentSongIndex<(songsList.size()1)){
playSong(currentSongIndex+1);
currentSongIndex=currentSongIndex+1;
}else{
//playfirstsong
playSong(0);
currentSongIndex=0;
}

}
});

/**
*Backbuttonclickevent
*PlaysprevioussongbycurrentSongIndex1
**/
btnPrevious.setOnClickListener(newView.OnClickListener(){

@Override
publicvoidonClick(Viewarg0){
if(currentSongIndex>0){
playSong(currentSongIndex1);
currentSongIndex=currentSongIndex1;
}else{
//playlastsong
playSong(songsList.size()1);
currentSongIndex=songsList.size()1;
}

}
});

/**
*ButtonClickeventforRepeatbutton
*Enablesrepeatflagtotrue
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

29/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

**/
btnRepeat.setOnClickListener(newView.OnClickListener(){

@Override
publicvoidonClick(Viewarg0){
if(isRepeat){
isRepeat=false;
Toast.makeText(getApplicationContext(),"RepeatisOFF",Toast.LENGT
btnRepeat.setImageResource(R.drawable.btn_repeat);
}else{
//makerepeattotrue
isRepeat=true;
Toast.makeText(getApplicationContext(),"RepeatisON",Toast.LENGTH
//makeshuffletofalse
isShuffle=false;
btnRepeat.setImageResource(R.drawable.btn_repeat_focused);
btnShuffle.setImageResource(R.drawable.btn_shuffle);
}
}
});

/**
*ButtonClickeventforShufflebutton
*Enablesshuffleflagtotrue
**/
btnShuffle.setOnClickListener(newView.OnClickListener(){

@Override
publicvoidonClick(Viewarg0){
if(isShuffle){
isShuffle=false;
Toast.makeText(getApplicationContext(),"ShuffleisOFF",Toast.LENG
btnShuffle.setImageResource(R.drawable.btn_shuffle);
}else{
//makerepeattotrue
isShuffle=true;
Toast.makeText(getApplicationContext(),"ShuffleisON",Toast.LENGT
//makeshuffletofalse
isRepeat=false;
btnShuffle.setImageResource(R.drawable.btn_shuffle_focused);
btnRepeat.setImageResource(R.drawable.btn_repeat);
}
}
});

/**
*ButtonClickeventforPlaylistclickevent
*Launcheslistactivitywhichdisplayslistofsongs
**/
btnPlaylist.setOnClickListener(newView.OnClickListener(){

@Override
publicvoidonClick(Viewarg0){
Intenti=newIntent(getApplicationContext(),PlayListActivity.class
startActivityForResult(i,100);
}
});

}
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

30/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

/**
*Receivingsongindexfromplaylistview
*andplaythesong
**/
@Override
protectedvoidonActivityResult(intrequestCode,
intresultCode,Intentdata){
super.onActivityResult(requestCode,resultCode,data);
if(resultCode==100){
currentSongIndex=data.getExtras().getInt("songIndex");
//playselectedsong
playSong(currentSongIndex);
}

/**
*Functiontoplayasong
*@paramsongIndexindexofsong
**/
publicvoidplaySong(intsongIndex){
//Playsong
try{
mp.reset();
mp.setDataSource(songsList.get(songIndex).get("songPath"));
mp.prepare();
mp.start();
//DisplayingSongtitle
StringsongTitle=songsList.get(songIndex).get("songTitle");
songTitleLabel.setText(songTitle);

//ChangingButtonImagetopauseimage
btnPlay.setImageResource(R.drawable.btn_pause);

//setProgressbarvalues
songProgressBar.setProgress(0);
songProgressBar.setMax(100);

//Updatingprogressbar
updateProgressBar();
}catch(IllegalArgumentExceptione){
e.printStackTrace();
}catch(IllegalStateExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
}

/**
*Updatetimeronseekbar
**/
publicvoidupdateProgressBar(){
mHandler.postDelayed(mUpdateTimeTask,100);
}

/**
*BackgroundRunnablethread
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

31/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

**/
privateRunnablemUpdateTimeTask=newRunnable(){
publicvoidrun(){
longtotalDuration=mp.getDuration();
longcurrentDuration=mp.getCurrentPosition();

//DisplayingTotalDurationtime
songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration
//Displayingtimecompletedplaying
songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDura

//Updatingprogressbar
intprogress=(int)(utils.getProgressPercentage(currentDuration,totalDu
//Log.d("Progress",""+progress);
songProgressBar.setProgress(progress);

//Runningthisthreadafter100milliseconds
mHandler.postDelayed(this,100);
}
};

/**
*
**/
@Override
publicvoidonProgressChanged(SeekBarseekBar,intprogress,booleanfromTouch){

/**
*Whenuserstartsmovingtheprogresshandler
**/
@Override
publicvoidonStartTrackingTouch(SeekBarseekBar){
//removemessageHandlerfromupdatingprogressbar
mHandler.removeCallbacks(mUpdateTimeTask);
}

/**
*Whenuserstopsmovingtheprogresshanlder
**/
@Override
publicvoidonStopTrackingTouch(SeekBarseekBar){
mHandler.removeCallbacks(mUpdateTimeTask);
inttotalDuration=mp.getDuration();
intcurrentPosition=utils.progressToTimer(seekBar.getProgress(),totalDuration

//forwardorbackwardtocertainseconds
mp.seekTo(currentPosition);

//updatetimerprogressagain
updateProgressBar();
}

/**
*OnSongPlayingcompleted
*ifrepeatisONplaysamesongagain
*ifshuffleisONplayrandomsong
**/
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

32/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

@Override
publicvoidonCompletion(MediaPlayerarg0){

//checkforrepeatisONorOFF
if(isRepeat){
//repeatisonplaysamesongagain
playSong(currentSongIndex);
}elseif(isShuffle){
//shuffleisonplayarandomsong
Randomrand=newRandom();
currentSongIndex=rand.nextInt((songsList.size()1)0+1)+0;
playSong(currentSongIndex);
}else{
//norepeatorshuffleONplaynextsong
if(currentSongIndex<(songsList.size()1)){
playSong(currentSongIndex+1);
currentSongIndex=currentSongIndex+1;
}else{
//playfirstsong
playSong(0);
currentSongIndex=0;
}
}
}

@Override
publicvoidonDestroy(){
super.onDestroy();
mp.release();
}

Sending files to Emulator SDCard (For Testing)


To test this app in your android emulator you need to load your emulator with some songs. You can
send files to emulator sdcard using adb tool which comes with Android SDK.
Navigate to your android SDK folder/platform-tools/ using command line. And using push command
you can send files to sdcard. (Start your emulator before performing push command)

platformtools>adbpush"c:\Songs\WhiteFlag.mp3""/sdcard/"
android load files to emulator sdcard
Run your application.

Share this article on


http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

33/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

53

465

32

Like

Tweet

You May Also Like

Android Developing

Android RSS Reader

Android RSS Reader

Android Custom

Flashlight Application

Application using SQLite

Application using SQLite

ListView with Image and

Part 2

Part 1

Text

563Comments

AndroidHive

Recommend 31

Share

Login

SortbyNewest

Jointhediscussion
MikeFrostCharvez 2daysago

wowwwwwwwww

Reply Share

PremK 10daysago

ThanksfortheTutorialdude!!!.Itreallyhelpedmealot:)
Butiamfacingaproblem,Wheneveritrytoclosetheapp,themediaplayerisgettingstopped.Ideally
ithastoplaysongsinthebackground,butitsnothappening.

Reply Share

RaviTamada

Mod >PremK 10daysago

TrykeepingtheMediaPlayercodeinabackgroundthreadmaybeanAsyncTask.
http://stackoverflow.com/quest...

Reply Share

AnujBhavsar 11daysago

ijustaddupyoursourcecodetoEclipsebutemulatorsaysappUnfortunatelyStopped
logCat:
080204:24:05.337:D/dalvikvm(573):NotlateenablingCheckJNI(alreadyon)
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

34/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

080204:24:05.337:D/dalvikvm(573):NotlateenablingCheckJNI(alreadyon)
080204:24:05.497:I/dalvikvm(573):TurningonJNIappbugworkaroundsfortargetSDKversion8...
080204:24:06.027:I/dalvikvm(573):threadid=3:reactingtosignal3
080204:24:06.143:I/dalvikvm(573):Wrotestacktracesto'/data/anr/traces.txt'
080204:24:06.427:D/dalvikvm(573):GC_FOR_ALLOCfreed91K,5%free5613K/5891K,paused
51ms
080204:24:06.557:I/dalvikvm(573):threadid=3:reactingtosignal3
080204:24:06.607:I/dalvikvm(573):Wrotestacktracesto'/data/anr/traces.txt'
080204:24:06.659:D/dalvikvm(573):GC_CONCURRENTfreed375K,9%free5741K/6279K,
paused6ms+4ms
seemore

Reply Share

Danish 14daysago

Sirwheneverirunyourmusicplayertherearemanyerrorshowingupontheerrorlogtheerrorlogin
below:
073009:54:58.828:E/AndroidRuntime(15304):FATALEXCEPTION:main
073009:54:58.828:E/AndroidRuntime(15304):Process:com.androidhive.musicplayer,PID:15304

073009:54:58.828:E/AndroidRuntime(15304):java.lang.RuntimeException:Unabletostartactivity
ComponentInfo{com.androidhive.musicplayer/com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity
java.lang.NullPointerException:Attempttogetlengthofnullarray
073009:54:58.828:E/AndroidRuntime(15304):at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2693)
073009:54:58.828:E/AndroidRuntime(15304):at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
073009:54:58.828:E/AndroidRuntime(15304):at
android.app.ActivityThread.access$900(ActivityThread.java:177)
seemore

Reply Share

PremK>Danish 10daysago

HiDanish,
Evenifacedthesameproblembutitgotresolvedafteraddingpermissionforaccessing
storageinAndroidManifest.xmlfile.
hereisthesnippetFYI
<usespermissionandroid:name="android.permission.READ_EXTERNAL_STORAGE"/>
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

35/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

<usespermissionandroid:name="android.permission.READ_EXTERNAL_STORAGE"/>

Reply Share

MohammadAkbari 16daysago

Thankyouforthisguide.:))

Reply Share

RaviTamada

Mod >MohammadAkbari 16daysago

Youarewelcome:)

Reply Share

Namrata amonthago

hi!thisisjustaminorissuebutitsstillabitofanagger.Theplayer.xmlandplaylist.xmlfileshavethe
layout_widthandlayout_heightsetto"match_parent"andthecompileristakingitasanerror.What
canireplaceitwith?Thanksinadvance.Therestisflawless.

Reply Share

Hetuka amonthago

thiscodeisveryhelpfulforme,thanksalot,nowiwanttoaddthosesongsinplaylistandaddto
favoritepleasegiveaanysolution,,,ThanksinAdvance.

Reply Share

hardik amonthago

idownloadedfullsourcecodebutiamgettingruntimeerroronit.unfortunatelyallhasstopworking
pleaseanyonetellmesoiutionforit..

Reply Share

akn amonthago

Imanagetoworkthiscode
1.Add"AndroidManifest.xml"thispermision(itshouldbebetween"android:versionName="1.0">:"to
<usessdkandroid:minsdkversion="8"/>)
<usespermissionandroid:name="android.permission.READ_EXTERNAL_STORAGE"/>
<usespermissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
2.Go"SongsManager.java"change:
finalStringMEDIA_PATH=newEnvironment().getExternalStorageDirectory().getPath()
3.Runcodeandgo"AndroidDeviceMonitor"(itisnearrunbuttoninAndroidStudio)waitlittlebitthen
find
"FileExplorer"tab
4.gomnt>sdcardthenselectthis.Nowyoushouldadd.mp3filetodothatlookabove
thereisabutton"pushafileontothedevice"clickthisthenchooseyour.mp3file.
5.ifstep4giveserror,itisaboutpermissionfindsdcardwithdrwxrxpermission
itcanbeunderstrogeforderoronlysdcardfolder.Incorrectsdcardthereisathingcalled
LOST.DIR
orwatchthisvideohttps://www.youtube.com/watch?...
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

36/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

orwatchthisvideohttps://www.youtube.com/watch?...

Reply Share

DHAVAL amonthago

Thanksfortutorial.butnowdaysiamfaceingoneissuethatoccuronlylolipopversion.Inmyappi
have10songandwhenitaptonextbuttonorperviousbuttonclickwheneversongisplayingthat
timeonCompletelisteneroncompletemethodfiremorethen5or6timeandsongautometicallyplay
onebyoneautomatically.stepforgettingthisissueclickonstartplaysongbuttonandandtapnext
buttonbeforsongstartingtimelessthen10secondthattimeautometically3or4songgoesaway.

Reply Share

NSB 2monthsago

Thankyouverymuchforthetutorial.Imademyownversionoutofit:)usingAndroidStudio
Hereismycodeatpaste.bin
1MainActivity:http://pastebin.com/ZJYr0Upj
2PlayerActivity:http://pastebin.com/wP6bAj5K
Thewholeprojectisuploadedhere:http://www.filedropper.com/bas...

Reply Share

Engedasew 2monthsago

howtochangesdcardmediapathintores/rawallcodesrelatedtothat...

Reply Share

NidhinKumar 2monthsago

Howtodothesamewithstreamingmusicusingjsoninsteadofreadingfromsdcard
1

Reply Share

NileshGiradkar 2monthsago

Codeisnotrunning...pleasemailmerunningcode..@nileshgiradkar1@gmail.com

Reply Share

RajeshBattala 3monthsago

Thanksforthewriteup.Ithelped

Reply Share

rAyMauSmAn 3monthsago

byusingthismediaplayeridonetodesignvideoplayeralso.thankusomuch...:)

Reply Share

rAyMauSmAn 3monthsago

plzanyonegivemeERdiagramandclassdiagramofthismediaplayer..

Reply Share

kartik 3monthsago

HyRaviTamadathankuverymuchforexplationandcode
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

37/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

butappisusingonlyinternalstorageandnotaccessingSDcard.ihavechagedmanifestfileandalso
usedEnvironment.getExternalStorageDirectory.getAbsolutePath()/.getPath()butitsnotworking.and
bystatusitsshowingMOUNTED.
Pleasehelp

Reply Share

gourav 3monthsago

TheappCrashesatbackpress,duetoRunnablemethod....haveanysolution4this???

Reply Share

KadamPriyanka 3monthsago

Ihaveasameproblem,whenIlaunchtheappitshowsunfortunatelymusicplayerhasstopped.please
helpme.
1

Reply Share

rAyMauSmAn>KadamPriyanka 3monthsago

changeurpath.gotosongmanger.andsetthepaththatisurdevicepath.

Reply Share

TabrezQureshi>rAyMauSmAn 3monthsago

bruitriedallmydevicepathbtitstillshowsunfortunatelymusicplayerhasstopped..

Reply Share

rAyMauSmAn>TabrezQureshi 3monthsago

addtoyourmanifest
<usespermission
android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<usespermission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
afterthisaddurrightpathinthisline
finalStringMEDIA_PATH=newString("/sdcard/Music")
mydevicepathis/sdcard/Musicaddurrightpathwithrightspelling

Reply Share

andro 3monthsago

Iamnotabletoaccessmyexternalmemorymp3files,butitsshowinginternalmemoryfiles.im
usingmysamsunggalaxys4asthedebugger.

Reply Share

kartik>andro 3monthsago

Iamfacingsameproblemwithmotoe
evenafterusingEnvironment.getExternalStorageDirectory.getAbsolutePath()/.getPath()
andisevenShowingMOUNTEDasitsstatus

http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

38/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

andisevenShowingMOUNTEDasitsstatus
pleasehelp

Reply Share

AhsanMisbah 4monthsago

Ihaveaprobleminmyapp,wheneverilaunchtheappitsaysUnfortunately,MusicPlayerhas
stopped.
Pleasehelpmetoovercomethis.
Nologcaterrorsihave.

Reply Share

AhsanMisbah>AhsanMisbah 4monthsago

gotthisoneinnotificationpanelofandroidstudio..
Launchingapplication:
com.example.ahsan.musicplayer/com.example.ahsan.musicplayer.AndroidBuildingMusicPlayerActivity.

DEVICESHELLCOMMAND:amstartn
"com.example.ahsan.musicplayer/com.example.ahsan.musicplayer.AndroidBuildingMusicPlayerActivity
aandroid.intent.action.MAINcandroid.intent.category.LAUNCHER
Starting:Intent{act=android.intent.action.MAINcat=[android.intent.category.LAUNCHER]
cmp=com.example.ahsan.musicplayer/.AndroidBuildingMusicPlayerActivity}

Reply Share

VincentKyalo 4monthsago

IimportedthesourcecodetomyeclipsebutgotthefollowingerroronmylogCat:
042021:03:35.603:E/AndroidRuntime(24908):FATALEXCEPTION:main

042021:03:35.603:E/AndroidRuntime(24908):java.lang.RuntimeException:Unabletostartactivity
ComponentInfo{com.androidhive.musicplayer/com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity
java.lang.IndexOutOfBoundsException:Invalidindex0,sizeis0
042021:03:35.603:E/AndroidRuntime(24908):at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2255)
042021:03:35.603:E/AndroidRuntime(24908):at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2309)
042021:03:35.603:E/AndroidRuntime(24908):at
android.app.ActivityThread.access$700(ActivityThread.java:157)
042021:03:35.603:E/AndroidRuntime(24908):at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1289)
seemore

Reply Share

Mcode 4monthsago
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

39/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

thiscodeabsolutelynotworking...itriedeverything...evenalterthecodeonupdatesuggestions....
:(

Reply Share

SudarshanMondal 4monthsago

IamgettingtheerroronmylogCat
040910:23:42.971:E/AndroidRuntime(2378):FATALEXCEPTION:main

040910:23:42.971:E/AndroidRuntime(2378):java.lang.RuntimeException:Unabletostartactivity
ComponentInfo{com.androidhive.musicplayer/com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity
java.lang.IndexOutOfBoundsException:Invalidindex0,sizeis0
040910:23:42.971:E/AndroidRuntime(2378):at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
040910:23:42.971:E/AndroidRuntime(2378):at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
040910:23:42.971:E/AndroidRuntime(2378):at
android.app.ActivityThread.access$600(ActivityThread.java:141)
040910:23:42.971:E/AndroidRuntime(2378):at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
seemore

Reply Share

Rio>SudarshanMondal 4monthsago

youmayneedtostopHandlerfunctionatonDestroy()function.justadd
mHandler.removeCallbacks(mUpdateTimeTask)atonDestroy()hopethiswork.

Reply Share

JakeHalawi 4monthsago

"Attemptocallgetdurationwithoutavalidmediaplayer(38,0)"Helpplease.

Reply Share

jhandal 4monthsago

Excelentcode..............................Iamtryngthesamefunctionality.......butwithoutshowingtheMedia
Player....................anyideaiswelcome...just.playingdirectlyfromthelist...........

Reply Share

ManikandanThivager 4monthsago

iamnotabletodownloadthesourcecode...canuplshelpmewiththat

Reply Share

RaymaUsman 5monthsago

ihaveproblemmymyapprunproperlybutwhenopenitinmytabitsgivingmeerrorunfortunately
mediaplayerstopworking.where'stheproblemisanyonetellmeplease..
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

40/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

mediaplayerstopworking.where'stheproblemisanyonetellmeplease..
1

Reply Share

jhandal>RaymaUsman 4monthsago

addtoyourmanifest
<usespermissionandroid:name="android.permission.READ_EXTERNAL_STORAGE"/>
<usespermissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
SongsManagerchange
finalStringMEDIA_PATH=Environment.getExternalStorageDirectory().getPath()+"/"
finallyaddsomemp3filesintheinternalstorageofyourphone.........................sdcardisnot
necessary

Reply Share

AhsanMisbah>jhandal 4monthsago

Hi
dearididthisbutappdoesnotlaunch,everytimeitshowsUnfortunately,MusicPlayer
hasstoped

Reply Share

MahfuzAhmed>jhandal 4monthsago

Canyoupleaseshowyourmanifestfile?

Reply Share

jhandal>MahfuzAhmed 4monthsago

Wherecangetthesource..
Thanks

Reply Share

RaymaUsman>jhandal 4monthsago

thankusomuch.islovemyproblemthanksagain:)

Reply Share

jhandal>RaymaUsman 4monthsago

Wherecandownloadthesource?
Thanks

Reply Share

RaymaUsman>jhandal 4monthsago

idoallthesestepsbutproblemissame.pleasehelpmeseriouslyireallyneed

Reply Share

ankitgajjar 5monthsago

Hello,
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

41/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

IwanttointegrateonlyOneSongtothismusicwhichisplayingcontinuously.Thatsongisinthe
androidprojectassestsfolder.Howcaniplaythatsong.givemeadvice.

Reply Share

ramankumar 5monthsago

iNeedMethodTogetSongInfoLikeSongArtist,album,Thumbnail...PleaseuploadTheseMethods
also..IwouldBeThankfulToYou!!

Reply Share

Manivel 5monthsago

Hi,
can'tgetstarted..Itsforceclosed.thepath"/sdcard/"onlyigave.andwhilerunthecmd'platform
tools>adbpush"c:\Songs\1.mp3""/sdcard/"'itshowtheerroris..'Readonlyaccess'likethat.soam
notabletoruncanyouplzhelpmetocommonpathforallthedevice..amusingAVDanddevicetoo..
Logcaterrorigues"fileordirectoryismissing"something

Reply Share

AtmiyaPatel 5monthsago

*****imhavingthiserrorpleasehelp*******

030914:29:26.9892398923989/com.mycompany.androidbuildingmusicplayerE/AndroidRuntime
FATALEXCEPTION:main
java.lang.RuntimeException:Unabletostartactivity
ComponentInfo{com.mycompany.androidbuildingmusicplayer/com.mycompany.androidbuildingmusicplayer.And
java.lang.IndexOutOfBoundsException:Invalidindex0,sizeis0
atandroid.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
atandroid.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
atandroid.app.ActivityThread.access$1500(ActivityThread.java:117)
atandroid.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
atandroid.os.Handler.dispatchMessage(Handler.java:99)
atandroid.os.Looper.loop(Looper.java:130)
atandroid.app.ActivityThread.main(ActivityThread.java:3683)
atjava.lang.reflect.Method.invokeNative(NativeMethod)
atjava.lang.reflect.Method.invoke(Method.java:507)
atcom.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:875)
atcom.android.internal.os.ZygoteInit.main(ZygoteInit.java:633)
seemore

Reply Share

Gee 6monthsago

HiRavi,isthereamethodtolayer2mp3sounds?Ihavebeengooglingbuticanfindanswers.Ihope
youcanhelp.thankyousomuchandmorepowertoyourblog.

Reply Share

Loadmorecomments
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

42/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

Subscribe

AddDisqustoyoursite

Privacy

Ravi Tamada
Hyderabad, INDIA

Subscribe to get latest updates to your inbox.


-- I dont spam!

Enter your email here

SUBSCRIBE

Advertise

AdvertiseHere

SolarWinds WireShark Tool


Easily Analyze Common
WireShark Packet Capture
Files, DL Free Tool.
www.solarwinds.com/nettools

http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

43/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

AndroidHive
30,960likes

LikePage

ContactUs

3friendslikethis

Tag Cloud
Action Bar

Adapter

Apps

Async

Chat

Dashboard

File Upload

Location

PHP
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

GPS

GCM

Grid

Grid View

Locale

Material Design

Navigation Drawer
Pinch

GDK

json

List View

Maps

facebook

Google Glass

Intermediate

Libstreaming

API

Camera

Database

Google

Google Plus

MySQL

Beginner

Fragments

Gestures

HTTP

Animation

PayPal

Progress Bar
44/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

Push Notifications
RecyclerView
SMS

REST

Sockets

sponsored
Twitter

sessions

Speech Input

SQLite

UI

View Pager

Quick Tips

Swipe

Video
Volley

Slim
Spinner

Tab View

Video Streaming
Wearable

xml

YouTube

Ravi Tamada
google.com/+RaviTamada
Theo di
13.220 ngi theo di

Most Popular
1

Android SQLite Database Tutorial - 1,141,789


views

How to connect Android with PHP, MySQL 1,074,341 views

Android JSON Parsing Tutorial - 964,586


views

Android Push Notifications using Google


Cloud Messaging (GCM), PHP and MySQL -

http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

45/46

13/8/2015

AndroidBuildingAudioPlayerTutorial

883,194 views
5

Android Custom ListView with Image and


Text - 837,963 views

Android

Sliding

Menu

using

Navigation

Drawer - 754,684 views


7

Android Login and Registration with PHP,


MySQL and SQLite - 702,385 views

Android GPS, Location Manager Tutorial 533,667 views

Android Tab Layout Tutorial - 516,150 views

10 Android Tab Layout with Swipeable Views 496,595 views

LondonAccommodations
UniqueRentalsinLondon.Bookaccommodationsfrom$49/night.

Copyright AndroidHive

http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/

Advertise . Privacy Policy . Terms & Conditions

46/46

You might also like