Professional Documents
Culture Documents
AndroidBuildingAudioPlayerTutorial
AdvertiseHere
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/
1/46
13/8/2015
AndroidBuildingAudioPlayerTutorial
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
3/46
13/8/2015
AndroidBuildingAudioPlayerTutorial
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/
4/46
13/8/2015
AndroidBuildingAudioPlayerTutorial
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,.)
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"/>
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
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.
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"));
}
}
}
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();
}
});
}
}
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;
}
}
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,
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();
}
}
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);
}
}
});
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;
}
}
});
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();
}
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);
}
}
});
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);
}
}
});
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;
}
}
}
your
AndroidManifest.xml
to
following
code.
Add
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();
}
platformtools>adbpush"c:\Songs\WhiteFlag.mp3""/sdcard/"
android load files to emulator sdcard
Run your application.
33/46
13/8/2015
AndroidBuildingAudioPlayerTutorial
53
465
32
Like
Tweet
Android Developing
Android Custom
Flashlight Application
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
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
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
Advertise
AdvertiseHere
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
Google Glass
Intermediate
Libstreaming
API
Camera
Database
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
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/
45/46
13/8/2015
AndroidBuildingAudioPlayerTutorial
883,194 views
5
Android
Sliding
Menu
using
Navigation
LondonAccommodations
UniqueRentalsinLondon.Bookaccommodationsfrom$49/night.
Copyright AndroidHive
http://www.androidhive.info/2012/03/androidbuildingaudioplayertutorial/
46/46