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.

Download Code

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.

MediaPlayer mp = new MediaPlayer();

// Set data source -
setDataSource("/sdcard/path_to_song");

// Play audio
mp.start();

// Pause audio
mp.pause();

// Reset mediaplayer
mp.reset();

// Get song length duration - in milliseconds
mp.getDuration();

// Get current duration - in milliseconds
mp.getCurrentDuration();

// Move song to particular second - used for Forward or Backward
mp.seekTo(positon); // position in milliseconds

// Check if song is playing or not
mp.isPlaying(); // returns true or false

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)

Android building audio player

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.

android audio player icons

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.

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/img_btn_play_pressed"
        android:state_focused="true"
        android:state_pressed="true" />
    <item android:drawable="@drawable/img_btn_play_pressed"
        android:state_focused="false"
        android:state_pressed="true" />
    <item android:drawable="@drawable/img_btn_play_pressed"
        	android:state_focused="true" />
    <item android: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 SeekBar using xml styles. In your drawable folder create to xml files and type the following code.

Changing SeekBar background:

<?xml version="1.0" encoding="utf-8"?>
 <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <clip>
        <bitmap xmlns: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>
</layer-list>

Changing SeekBar Progress:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background"
        android:drawable="@drawable/img_seekbar_bg"
        android:dither="true">
    </item>
    <item android: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"
    />
</layer-list>

Actual seekbar which uses above xml files:

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

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/player_background"> 

    <!-- Player Header -->
    <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">

        <!-- Song Title -->
        <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="The Good, The Bad And The Ugly"
            android:layout_marginTop="10dp"/>

        <!-- Playlist button -->
        <ImageButton
            android:id="@+id/btnPlaylist"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:src="@drawable/btn_playlist"
            android:background="@null"/>
    </LinearLayout>

    <!-- Song Thumbnail Image -->
    <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">
    	<ImageView android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/adele"/>
    </LinearLayout>

    <!-- Player Footer -->
    <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">

        <!-- Player Buttons -->
        <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">
            <!-- Previous Button -->
            <ImageButton
                android:id="@+id/btnPrevious"
                android:src="@drawable/btn_previous"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@null"/>
            <!-- Backward Button -->
            <ImageButton
                android:id="@+id/btnBackward"
                android:src="@drawable/btn_backward"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@null"/>
            <!-- Play Button -->
            <ImageButton
                android:id="@+id/btnPlay"
                android:src="@drawable/btn_play"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@null"/>
            <!-- Forward Button -->
            <ImageButton
                android:id="@+id/btnForward"
                android:src="@drawable/btn_forward"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@null"/>
            <!-- Next Button -->
            <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>

    <!-- Progress Bar/Seek bar -->
    <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"/>

    <!-- Timer Display -->
    <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">
        <!-- Current Duration Label -->
        <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"/>
        <!-- Total Duration Label -->
        <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>

    <!-- Repeat / Shuffle buttons -->
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/timerDisplay"
        android:gravity="center">
        <!-- Repeat Button -->
        <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"/>

        <!-- Shuffle Button -->
         <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.

android audio player

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.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Selector style for listrow -->
<item
 android:state_selected="false"
    android:state_pressed="false"
    android:drawable="@drawable/gradient_bg" />
<item android:state_pressed="true"
    android:drawable="@drawable/gradient_bg_hover" />
<item android: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.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns: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.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns: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"
        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.

Android audio player playlist

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.

package com.androidhive.musicplayer;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;

public class SongsManager {
	// SDCard Path
	final String MEDIA_PATH = new String("/sdcard/");
	private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

	// Constructor
	public SongsManager(){

	}

	/**
	 * Function to read all mp3 files from sdcard
	 * and store the details in ArrayList
	 * */
	public ArrayList<HashMap<String, String>> getPlayList(){
		File home = new File(MEDIA_PATH);

		if (home.listFiles(new FileExtensionFilter()).length > 0) {
			for (File file : home.listFiles(new FileExtensionFilter())) {
				HashMap<String, String> song = new HashMap<String, String>();
				song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
				song.put("songPath", file.getPath());

				// Adding each song to SongList
				songsList.add(song);
			}
		}
		// return songs list array
		return songsList;
	}

	/**
	 * Class to filter files which are having .mp3 extension
	 * */
	class FileExtensionFilter implements FilenameFilter {
		public boolean accept(File dir, String name) {
			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

package com.androidhive.musicplayer;

import java.util.ArrayList;
import java.util.HashMap;

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

public class PlayListActivity extends ListActivity {
	// Songs list
	public ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.playlist);

		ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();

		SongsManager plm = new SongsManager();
		// get all songs from sdcard
		this.songsList = plm.getPlayList();

		// looping through playlist
		for (int i = 0; i < songsList.size(); i++) {
			// creating new HashMap
			HashMap<String, String> song = songsList.get(i);

			// adding HashList to ArrayList
			songsListData.add(song);
		}

		// Adding menuItems to ListView
		ListAdapter adapter = new SimpleAdapter(this, songsListData,
				R.layout.playlist_item, new String[] { "songTitle" }, new int[] {
						R.id.songTitle });

		setListAdapter(adapter);

		// selecting single ListView item
		ListView lv = getListView();
		// listening to single listitem click
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// getting listitem index
				int songIndex = position;

				// Starting new intent
				Intent in = new Intent(getApplicationContext(),
						AndroidBuildingMusicPlayerActivity.class);
				// Sending songIndex to PlayerActivity
				in.putExtra("songIndex", songIndex);
				setResult(100, in);
				// Closing PlayListView
				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.

package com.androidhive.musicplayer;

public class Utilities {

	/**
	 * Function to convert milliseconds time to
	 * Timer Format
	 * Hours:Minutes:Seconds
	 * */
	public String milliSecondsToTimer(long milliseconds){
		String finalTimerString = "";
		String secondsString = "";

		// Convert total duration into time
		   int hours = (int)( milliseconds / (1000*60*60));
		   int minutes = (int)(milliseconds % (1000*60*60)) / (1000*60);
		   int seconds = (int) ((milliseconds % (1000*60*60)) % (1000*60) / 1000);
		   // Add hours if there
		   if(hours > 0){
			   finalTimerString = hours + ":";
		   }

		   // Prepending 0 to seconds if it is one digit
		   if(seconds < 10){
			   secondsString = "0" + seconds;
		   }else{
			   secondsString = "" + seconds;}

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

		// return timer string
		return finalTimerString;
	}

	/**
	 * Function to get Progress percentage
	 * @param currentDuration
	 * @param totalDuration
	 * */
	public int getProgressPercentage(long currentDuration, long totalDuration){
		Double percentage = (double) 0;

		long currentSeconds = (int) (currentDuration / 1000);
		long totalSeconds = (int) (totalDuration / 1000);

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

		// return percentage
		return percentage.intValue();
	}

	/**
	 * Function to change progress to timer
	 * @param progress -
	 * @param totalDuration
	 * returns current duration in milliseconds
	 * */
	public int progressToTimer(int progress, int totalDuration) {
		int currentDuration = 0;
		totalDuration = (int) (totalDuration / 1000);
		currentDuration = (int) ((((double)progress) / 100) * totalDuration);

		// return current duration in milliseconds
		return currentDuration * 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.

public class AndroidBuildingMusicPlayerActivity extends Activity
       implements OnCompletionListener, SeekBar.OnSeekBarChangeListener {

Now declare all variable needed for this audio player class.

public class AndroidBuildingMusicPlayerActivity extends Activity
       implements OnCompletionListener, SeekBar.OnSeekBarChangeListener {

	private ImageButton btnPlay;
	private ImageButton btnForward;
	private ImageButton btnBackward;
	private ImageButton btnNext;
	private ImageButton btnPrevious;
	private ImageButton btnPlaylist;
	private ImageButton btnRepeat;
	private ImageButton btnShuffle;
	private SeekBar songProgressBar;
	private TextView songTitleLabel;
	private TextView songCurrentDurationLabel;
	private TextView songTotalDurationLabel;
	// Media Player
	private  MediaPlayer mp;
	// Handler to update UI timer, progress bar etc,.
	private Handler mHandler = new Handler();;
	private SongsManager songManager;
	private Utilities utils;
	private int seekForwardTime = 5000; // 5000 milliseconds
	private int seekBackwardTime = 5000; // 5000 milliseconds
	private int currentSongIndex = 0;
	private boolean isShuffle = false;
	private boolean isRepeat = false;
	private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

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

// All player buttons
		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 = new MediaPlayer();
		songManager = new SongsManager();
		utils = new Utilities();

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

		// Getting all songs list
		songsList = songManager.getPlayList();

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.

/**
		 * Button Click event for Play list click event
		 * Launches list activity which displays list of songs
		 * */
		btnPlaylist.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent i = new Intent(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)

/**
	 * Receiving song index from playlist view
	 * and play the song
	 * */
	@Override
    protected void onActivityResult(int requestCode,
                                     int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 100){
         	 currentSongIndex = data.getExtras().getInt("songIndex");
         	 // play selected song
             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.

/**
	 * Function to play a song
	 * @param songIndex - index of song
	 * */
	public void  playSong(int songIndex){
		// Play song
		try {
        	mp.reset();
			mp.setDataSource(songsList.get(songIndex).get("songPath"));
			mp.prepare();
			mp.start();
			// Displaying Song title
			String songTitle = songsList.get(songIndex).get("songTitle");
        	songTitleLabel.setText(songTitle);

        	// Changing Button Image to pause image
			btnPlay.setImageResource(R.drawable.btn_pause);

			// set Progress bar values
			songProgressBar.setProgress(0);
			songProgressBar.setMax(100);

			// Updating progress bar
			updateProgressBar();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			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

/**
		 * Forward button click event
		 * Forwards song specified seconds
		 * */
		btnForward.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// get current song position
				int currentPosition = mp.getCurrentPosition();
				// check if seekForward time is lesser than song duration
				if(currentPosition + seekForwardTime <= mp.getDuration()){
					// forward song
					mp.seekTo(currentPosition + seekForwardTime);
				}else{
					// forward to end position
					mp.seekTo(mp.getDuration());
				}
			}
		});

Backward button click event – moves song to specified number of seconds backward

/**
		 * Backward button click event
		 * Backward song to specified seconds
		 * */
		btnBackward.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// get current song position
				int currentPosition = mp.getCurrentPosition();
				// check if seekBackward time is greater than 0 sec
				if(currentPosition - seekBackwardTime >= 0){
					// forward song
					mp.seekTo(currentPosition - seekBackwardTime);
				}else{
					// backward to starting position
					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

/**
		 * Next button click event
		 * Plays next song by taking currentSongIndex + 1
		 * */
		btnNext.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// check if next song is there or not
				if(currentSongIndex < (songsList.size() - 1)){
					playSong(currentSongIndex + 1);
					currentSongIndex = currentSongIndex + 1;
				}else{
					// play first song
					playSong(0);
					currentSongIndex = 0;
				}

			}
		});

Back button click event – which plays previous song if presents or plays last song

/**
		 * Back button click event
		 * Plays previous song by currentSongIndex - 1
		 * */
		btnPrevious.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if(currentSongIndex > 0){
					playSong(currentSongIndex - 1);
					currentSongIndex = currentSongIndex - 1;
				}else{
					// play last song
					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

/**
	 * Update timer on seekbar
	 * */
	public void updateProgressBar() {
        mHandler.postDelayed(mUpdateTimeTask, 100);
    }	

	/**
	 * Background Runnable thread
	 * */
	private Runnable mUpdateTimeTask = new Runnable() {
		   public void run() {
			   long totalDuration = mp.getDuration();
			   long currentDuration = mp.getCurrentPosition();

			   // Displaying Total Duration time
			   songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
			   // Displaying time completed playing
			   songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));

			   // Updating progress bar
			   int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
			   //Log.d("Progress", ""+progress);
			   songProgressBar.setProgress(progress);

			   // Running this thread after 100 milliseconds
		       mHandler.postDelayed(this, 100);
		   }
		};

	/**
	 *
	 * */
	@Override
	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {

	}

	/**
	 * When user starts moving the progress handler
	 * */
	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// remove message Handler from updating progress bar
		mHandler.removeCallbacks(mUpdateTimeTask);
    }

	/**
	 * When user stops moving the progress hanlder
	 * */
	@Override
    public void onStopTrackingTouch(SeekBar seekBar) {
		mHandler.removeCallbacks(mUpdateTimeTask);
		int totalDuration = mp.getDuration();
		int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);

		// forward or backward to certain seconds
		mp.seekTo(currentPosition);

		// update timer progress again
		updateProgressBar();
    }

Repeat button click event

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.

/**
		 * Button Click event for Repeat button
		 * Enables repeat flag to true
		 * */
		btnRepeat.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if(isRepeat){
					isRepeat = false;
					Toast.makeText(getApplicationContext(), "Repeat is OFF", Toast.LENGTH_SHORT).show();
					btnRepeat.setImageResource(R.drawable.btn_repeat);
				}else{
					// make repeat to true
					isRepeat = true;
					Toast.makeText(getApplicationContext(), "Repeat is ON", Toast.LENGTH_SHORT).show();
					// make shuffle to false
					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.

/**
		 * Button Click event for Shuffle button
		 * Enables shuffle flag to true
		 * */
		btnShuffle.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if(isShuffle){
					isShuffle = false;
					Toast.makeText(getApplicationContext(), "Shuffle is OFF", Toast.LENGTH_SHORT).show();
					btnShuffle.setImageResource(R.drawable.btn_shuffle);
				}else{
					// make repeat to true
					isShuffle= true;
					Toast.makeText(getApplicationContext(), "Shuffle is ON", Toast.LENGTH_SHORT).show();
					// make shuffle to false
					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.

/**
	 * On Song Playing completed
	 * if repeat is ON play same song again
	 * if shuffle is ON play random song
	 * */
	@Override
	public void onCompletion(MediaPlayer arg0) {

		// check for repeat is ON or OFF
		if(isRepeat){
			// repeat is on play same song again
			playSong(currentSongIndex);
		} else if(isShuffle){
			// shuffle is on - play a random song
			Random rand = new Random();
			currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
			playSong(currentSongIndex);
		} else{
			// no repeat or shuffle ON - play next song
			if(currentSongIndex < (songsList.size() - 1)){
				playSong(currentSongIndex + 1);
				currentSongIndex = currentSongIndex + 1;
			}else{
				// play first song
				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.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidhive.musicplayer"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android: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">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

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

</manifest>
<!-- AndroidBuildingMusicPlayerActivity -->

Final Code

Following is complete code for the AndroidBuildingMusicPlayerActivity.java class.

package com.androidhive.musicplayer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidBuildingMusicPlayerActivity extends Activity implements OnCompletionListener, SeekBar.OnSeekBarChangeListener {

	private ImageButton btnPlay;
	private ImageButton btnForward;
	private ImageButton btnBackward;
	private ImageButton btnNext;
	private ImageButton btnPrevious;
	private ImageButton btnPlaylist;
	private ImageButton btnRepeat;
	private ImageButton btnShuffle;
	private SeekBar songProgressBar;
	private TextView songTitleLabel;
	private TextView songCurrentDurationLabel;
	private TextView songTotalDurationLabel;
	// Media Player
	private  MediaPlayer mp;
	// Handler to update UI timer, progress bar etc,.
	private Handler mHandler = new Handler();;
	private SongsManager songManager;
	private Utilities utils;
	private int seekForwardTime = 5000; // 5000 milliseconds
	private int seekBackwardTime = 5000; // 5000 milliseconds
	private int currentSongIndex = 0;
	private boolean isShuffle = false;
	private boolean isRepeat = false;
	private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.player);

		// All player buttons
		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 = new MediaPlayer();
		songManager = new SongsManager();
		utils = new Utilities();

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

		// Getting all songs list
		songsList = songManager.getPlayList();

		// By default play first song
		playSong(0);

		/**
		 * Play button click event
		 * plays a song and changes button to pause image
		 * pauses a song and changes button to play image
		 * */
		btnPlay.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// check for already playing
				if(mp.isPlaying()){
					if(mp!=null){
						mp.pause();
						// Changing button image to play button
						btnPlay.setImageResource(R.drawable.btn_play);
					}
				}else{
					// Resume song
					if(mp!=null){
						mp.start();
						// Changing button image to pause button
						btnPlay.setImageResource(R.drawable.btn_pause);
					}
				}

			}
		});

		/**
		 * Forward button click event
		 * Forwards song specified seconds
		 * */
		btnForward.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// get current song position
				int currentPosition = mp.getCurrentPosition();
				// check if seekForward time is lesser than song duration
				if(currentPosition + seekForwardTime <= mp.getDuration()){
					// forward song
					mp.seekTo(currentPosition + seekForwardTime);
				}else{
					// forward to end position
					mp.seekTo(mp.getDuration());
				}
			}
		});

		/**
		 * Backward button click event
		 * Backward song to specified seconds
		 * */
		btnBackward.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// get current song position
				int currentPosition = mp.getCurrentPosition();
				// check if seekBackward time is greater than 0 sec
				if(currentPosition - seekBackwardTime >= 0){
					// forward song
					mp.seekTo(currentPosition - seekBackwardTime);
				}else{
					// backward to starting position
					mp.seekTo(0);
				}

			}
		});

		/**
		 * Next button click event
		 * Plays next song by taking currentSongIndex + 1
		 * */
		btnNext.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// check if next song is there or not
				if(currentSongIndex < (songsList.size() - 1)){
					playSong(currentSongIndex + 1);
					currentSongIndex = currentSongIndex + 1;
				}else{
					// play first song
					playSong(0);
					currentSongIndex = 0;
				}

			}
		});

		/**
		 * Back button click event
		 * Plays previous song by currentSongIndex - 1
		 * */
		btnPrevious.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if(currentSongIndex > 0){
					playSong(currentSongIndex - 1);
					currentSongIndex = currentSongIndex - 1;
				}else{
					// play last song
					playSong(songsList.size() - 1);
					currentSongIndex = songsList.size() - 1;
				}

			}
		});

		/**
		 * Button Click event for Repeat button
		 * Enables repeat flag to true
		 * */
		btnRepeat.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if(isRepeat){
					isRepeat = false;
					Toast.makeText(getApplicationContext(), "Repeat is OFF", Toast.LENGTH_SHORT).show();
					btnRepeat.setImageResource(R.drawable.btn_repeat);
				}else{
					// make repeat to true
					isRepeat = true;
					Toast.makeText(getApplicationContext(), "Repeat is ON", Toast.LENGTH_SHORT).show();
					// make shuffle to false
					isShuffle = false;
					btnRepeat.setImageResource(R.drawable.btn_repeat_focused);
					btnShuffle.setImageResource(R.drawable.btn_shuffle);
				}
			}
		});

		/**
		 * Button Click event for Shuffle button
		 * Enables shuffle flag to true
		 * */
		btnShuffle.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if(isShuffle){
					isShuffle = false;
					Toast.makeText(getApplicationContext(), "Shuffle is OFF", Toast.LENGTH_SHORT).show();
					btnShuffle.setImageResource(R.drawable.btn_shuffle);
				}else{
					// make repeat to true
					isShuffle= true;
					Toast.makeText(getApplicationContext(), "Shuffle is ON", Toast.LENGTH_SHORT).show();
					// make shuffle to false
					isRepeat = false;
					btnShuffle.setImageResource(R.drawable.btn_shuffle_focused);
					btnRepeat.setImageResource(R.drawable.btn_repeat);
				}
			}
		});

		/**
		 * Button Click event for Play list click event
		 * Launches list activity which displays list of songs
		 * */
		btnPlaylist.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent i = new Intent(getApplicationContext(), PlayListActivity.class);
				startActivityForResult(i, 100);
			}
		});

	}

	/**
	 * Receiving song index from playlist view
	 * and play the song
	 * */
	@Override
    protected void onActivityResult(int requestCode,
                                     int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 100){
         	 currentSongIndex = data.getExtras().getInt("songIndex");
         	 // play selected song
             playSong(currentSongIndex);
        }

    }

	/**
	 * Function to play a song
	 * @param songIndex - index of song
	 * */
	public void  playSong(int songIndex){
		// Play song
		try {
        	mp.reset();
			mp.setDataSource(songsList.get(songIndex).get("songPath"));
			mp.prepare();
			mp.start();
			// Displaying Song title
			String songTitle = songsList.get(songIndex).get("songTitle");
        	songTitleLabel.setText(songTitle);

        	// Changing Button Image to pause image
			btnPlay.setImageResource(R.drawable.btn_pause);

			// set Progress bar values
			songProgressBar.setProgress(0);
			songProgressBar.setMax(100);

			// Updating progress bar
			updateProgressBar();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Update timer on seekbar
	 * */
	public void updateProgressBar() {
        mHandler.postDelayed(mUpdateTimeTask, 100);
    }	

	/**
	 * Background Runnable thread
	 * */
	private Runnable mUpdateTimeTask = new Runnable() {
		   public void run() {
			   long totalDuration = mp.getDuration();
			   long currentDuration = mp.getCurrentPosition();

			   // Displaying Total Duration time
			   songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
			   // Displaying time completed playing
			   songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));

			   // Updating progress bar
			   int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
			   //Log.d("Progress", ""+progress);
			   songProgressBar.setProgress(progress);

			   // Running this thread after 100 milliseconds
		       mHandler.postDelayed(this, 100);
		   }
		};

	/**
	 *
	 * */
	@Override
	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {

	}

	/**
	 * When user starts moving the progress handler
	 * */
	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// remove message Handler from updating progress bar
		mHandler.removeCallbacks(mUpdateTimeTask);
    }

	/**
	 * When user stops moving the progress hanlder
	 * */
	@Override
    public void onStopTrackingTouch(SeekBar seekBar) {
		mHandler.removeCallbacks(mUpdateTimeTask);
		int totalDuration = mp.getDuration();
		int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);

		// forward or backward to certain seconds
		mp.seekTo(currentPosition);

		// update timer progress again
		updateProgressBar();
    }

	/**
	 * On Song Playing completed
	 * if repeat is ON play same song again
	 * if shuffle is ON play random song
	 * */
	@Override
	public void onCompletion(MediaPlayer arg0) {

		// check for repeat is ON or OFF
		if(isRepeat){
			// repeat is on play same song again
			playSong(currentSongIndex);
		} else if(isShuffle){
			// shuffle is on - play a random song
			Random rand = new Random();
			currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
			playSong(currentSongIndex);
		} else{
			// no repeat or shuffle ON - play next song
			if(currentSongIndex < (songsList.size() - 1)){
				playSong(currentSongIndex + 1);
				currentSongIndex = currentSongIndex + 1;
			}else{
				// play first song
				playSong(0);
				currentSongIndex = 0;
			}
		}
	}

	@Override
	 public void onDestroy(){
	 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)

platform-tools> adb push "c:\Songs\White Flag.mp3" "/sdcard/"
android load files to emulator sdcard

Run your application.

Android building music player
Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • b0wter

    I have written a method to scan any folder, including all its subfolders for all files matching any wanted file extension.

    You can find the code here:
    http://pastebin.com/krxV64R3

    The method “createAudioExtensionsList()” creates a list of file extensions that you want to find. In your case that would only be mp3 files so you have to remove the other entries.

    “getFileExtension(…)” is a simple method to get the extension of a file.

    “getFilesInFolder(…)” is a function that calls itself recursively to scan a folder and all its subfolders for the file with the extensions that you give it as parameters. If you want to scan the whole sdcard you just pass the that to the function! (be aware that different Android ROMs might have different naming conventions! There is a method to get the root path of the sd card but I dont remember, so you have to look it up yourself)

    • kanmane

      Hi Mr.bowter…thank u so much fr yr reply..but the Url which u have given is not working..i couldn’t able to connect to that site…can u pls check out n let me know the code..Thank u once again…Waiting for yr reply….

    • Andi

      I already tried it, but I can’t call the function “getFilesInFolder”. Eclipse keep saying ” The method getFilesInFolder(File, ArrayList) in the type SongsManager is not applicable for the arguments (String,
      ArrayList)”. Can you please help me? Thank you.

  • b0wter

    see the post above, I’ve posted something that works for me :]

  • Revoseven

    Is there someone who is willing to send source code for android music player that runs smoothly. I would be very grateful to those of you who have helped me. you can get sent to the email: ceo.revoseven @ gmail.com. thanks before

  • suraj

    how…what was d problem?

  • Nagaganesh

    Hai Ravi.

    How to get mp3 songs Thumbnail from sdcard in android.

  • wodzu96

    Hello. Thanks for the tutorial! But I think that there is better way to find songs in the phone. You can find it like that:

    public ArrayList<HashMap> getPlayList(){

    Cursor cursor = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String [] {“ARTIST”, “DURATION”, “TITLE”, “_DATA”, “ALBUM”}, null, null, null);

    while(cursor.moveToNext()) {

    HashMap song = new HashMap();

    song.put(“artist”, cursor.getString(0));

    song.put(“duration”, cursor.getString(1));

    song.put(“songTitle”, cursor.getString(2));

    song.put(“songPath”,cursor.getString(3));

    song.put(“album”,cursor.getString(4));

    // Adding each song to SongList

    songsList.add(song);

    }

    return songsList;

    }

    Thanks to this you can also get name of artists, albums and duration.

  • John Pavlecich

    For anyone having trouble with the IndexOutOfBoundsException, it is because it is not finding any music on your sdcard.

    Line 80: playSong(0); throws an indexOutBoundsException when it finds no music (getPlaylist() returns a blank list so 0 is not a proper index).

    I fixed it by changing the the directory it starts in so it actually finds music. Here is a code snippet to set the directory as the music folder. Make sure you actually have music there or you’ll still get the error.

    In SongsManager.java: getPlaylist() method:

    File home = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);

    The original tutorial probably should have a had check on the size to make sure the playlist really had something in it rather than trying to play the first song off the bat which crashes the program if no music exists.

    if(songsList.size() >0){
    // By default play first song
    playSong(0);
    }

  • John Pavlecich

    It is not finding music on your sdcard. In the class AndroidBuildingMusicPlayerActivity, it attempts to playSong(0). If the songsManager finds no music, this will throw that exception. You can either change where it is looking for music or prevent the app from playing the first song. See my post at the top.

  • how building audio list from web service, any help?

  • Don Peter

    Man its an error during parsing sdcard for mp3 files.

    please do correct it. Its in the fuctiongetplaylist in SongsManager

  • raghav

    hey grt work …..
    can u help with my app coz i have to build an audio player which instead of using the plugins use decoding, i.e it is more of decoder bt i dont how to implement it in android

  • if u geted message ” forced to close” u change android:name=”.AndroidBuildingMusicPlayerActivity” to android:name=”com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity”
    i done

    • Bun Tith

      For me no done can you help me
      thank

    • HoosHmand rostami

      For me no done
      can you help me please

      thank

      • spy

        i think the the problem is that you dont have any mp3 on device. And app plays first song on start but doesnt find it ;P

  • Don Peter

    Did you correct the force close error in the app.
    if you did please share how..

    • siraj

      you have to have mp3 music in emulator device.

  • Raaaj

    Thanks for making such a great job. However, I have these problems in eclipse when I run the player as android application on my PC. Please help me fix these errors.

    04-24 18:26:22.245: E/Trace(790): error opening trace file: No such file or directory (2)
    04-24 18:26:23.095: D/dalvikvm(790): GC_FOR_ALLOC freed 73K, 8% free 2527K/2724K, paused 47ms, total 50ms
    04-24 18:26:23.225: D/dalvikvm(790): GC_CONCURRENT freed 5K, 6% free 2972K/3148K, paused 19ms+9ms, total 75ms
    04-24 18:26:23.225: D/dalvikvm(790): WAIT_FOR_CONCURRENT_GC blocked 4ms
    04-24 18:26:23.435: D/AndroidRuntime(790): Shutting down VM
    04-24 18:26:23.435: W/dalvikvm(790): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
    04-24 18:26:23.476: E/AndroidRuntime(790): FATAL EXCEPTION: main
    04-24 18:26:23.476: E/AndroidRuntime(790): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rajumediaplayer/com.rajumediaplayer.RajuMediaPlayer}: java.lang.NullPointerException
    04-24 18:26:23.476: E/AndroidRuntime(790): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
    04-24 18:26:23.476: E/AndroidRuntime(790): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
    04-24 18:26:23.476: E/AndroidRuntime(790): at android.app.ActivityThread.access$600(ActivityThread.java:141)
    04-24 18:26:23.476: E/AndroidRuntime(790): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
    04-24 18:26:23.476: E/AndroidRuntime(790): at android.os.Handler.dispatchMessage(Handler.java:99)
    04-24 18:26:23.476: E/AndroidRuntime(790): at android.os.Looper.loop(Looper.java:137)
    04-24 18:26:23.476: E/AndroidRuntime(790): at android.app.ActivityThread.main(ActivityThread.java:5041)
    04-24 18:26:23.476: E/AndroidRuntime(790): at java.lang.reflect.Method.invokeNative(Native Method)
    04-24 18:26:23.476: E/AndroidRuntime(790): at java.lang.reflect.Method.invoke(Method.java:511)
    04-24 18:26:23.476: E/AndroidRuntime(790): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    04-24 18:26:23.476: E/AndroidRuntime(790): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    04-24 18:26:23.476: E/AndroidRuntime(790): at dalvik.system.NativeStart.main(Native Method)
    04-24 18:26:23.476: E/AndroidRuntime(790): Caused by: java.lang.NullPointerException
    04-24 18:26:23.476: E/AndroidRuntime(790): at com.rajumediaplayer.SongsManager.getPlayList(SongsManager.java:24)
    04-24 18:26:23.476: E/AndroidRuntime(790): at com.rajumediaplayer.RajuMediaPlayer.onCreate(RajuMediaPlayer.java:76)
    04-24 18:26:23.476: E/AndroidRuntime(790): at android.app.Activity.performCreate(Activity.java:5104)
    04-24 18:26:23.476: E/AndroidRuntime(790): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
    04-24 18:26:23.476: E/AndroidRuntime(790): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
    04-24 18:26:23.476: E/AndroidRuntime(790): … 11 more
    04-24 18:26:23.715: D/dalvikvm(790): GC_CONCURRENT freed 57K, 6% free 3316K/3496K, paused 17ms+4ms, total 237ms
    04-24 18:26:28.282: I/Process(790): Sending signal. PID: 790 SIG: 9

  • Myo Htet Aung

    Hi Ravi,

    your code works like charm. Now I have song array list which came through server and populated in list view.I want to implement my codes with your music player,so that I have been looking through your codes and fount out MEDIA_PATH string which is pointed to sdcard. My question is that how could I change this path to load my songs list array properly ? Thanks in advance !

    • Sagar

      Download song list xml file and parse it search xml parsing tutorial on same website

  • zen kun

    i cant download the code 🙁

  • zen kun

    ok i download the code and testing in my nexus isnt working the folder stuff, and could be a slow task i guess scanning so in song manager i changed this:

    public ArrayList<HashMap> getPlayList(Context context){

    String[] projection = {

    MediaStore.Audio.Media._ID,

    MediaStore.Audio.Media.ARTIST,

    MediaStore.Audio.Media.TITLE,

    MediaStore.Audio.Media.DATA,

    MediaStore.Audio.Media.DISPLAY_NAME,

    MediaStore.Audio.Media.DURATION

    };

    String selection = MediaStore.Audio.Media.IS_MUSIC + ” != 0″;

    Cursor cursor = context.getContentResolver().query(

    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,

    projection,

    selection,

    null,

    null);

    if(cursor!=null)

    {

    while(cursor.moveToNext()) {

    HashMap song = new HashMap();

    String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));

    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));

    song.put(“songTitle”, title);

    song.put(“songPath”, path);

    songsList.add(song);

    }

    }

    return songsList;

    }

    • Abioye Samson

      thumps up

    • I’m unable to implement your code. Could you please post whole code for SongManager. Thanks!

  • lamorozzo

    Thank you for this interesting application.

    however when I started to run it / launch it.. it shows “You project contains error(s) , Please fix them before running the application”…

    I recheck all lines in all imported files and found some in the Utilities.java

    Implicit super constructor Object() is undefined for default constructor. Must define an explicit constructor

    and for string declaration, I got: String cannot be resolved to a type

    I tried to solve it in different ways with no results

    thank you helping

  • Varun

    It is showing content is not allowed in prolog error

  • Varun

    Error:

    Description Resource Path Location Type

    Parser exception for /AlphaMusicPlayer/AndroidManifest.xml: The processing instruction target matching “[xX][mM][lL]” is not allowed. AlphaMusicPlayer line 1 Android ADT Problem

    This is the manifest file and it is showing me the ADT problem. I couldn’t find any answer. I would be obliged if anyone can help me fix it? D:

  • Jose Carlos Gutierrez

    This is just what I was looking for. Thansk you so much…

  • Micheal

    Hi, Thanks for the code, it works best for .mp3 files. But when I tried to play .wav file the seek to feature is not working properly. Do you know/have any workaround for this issue?

  • Guest

    Simple question.
    On which Android API does this run?

    • Abhilash

      I mean the version.

  • keshav

    Hi ravi
    right now your taking the files by “SDCARD” , if it is url based how to play… please explain this.

  • Bun Tith

    Hi
    Thank you for tutorials
    I want to ask you while i ran this apps it show me a message Force Close
    I don’t know what’s wrong
    Please help me to solve this problem
    thank

  • yudex gerah polo
    • To fix error simply add final String MEDIA_PATH = new String(Environment.getExternalStorageDirectory().getPath() +”/sdcard/”);

      in song manger then create sdcard folder in your external storage and add songs in it install and tada!!!!!!!

  • suprayitno

    i’ve an error message.

    Unfonately AndroidBuildingMusicPlayer has stopped…

    but there’s no such error in your coding

    please help me

    • To fix error simply add final String MEDIA_PATH = new String(Environment.getExternalStorageDirectory().getPath() +”/sdcard/”);

      in song manger then create sdcard folder in your external storage and add songs in it install and tada!!!!!!!1

  • Writwick Daz

    I am loving AndroidHive because of so descriptive UI designing tutorial.. :thumbsup:
    Keep up the good work.. Helped me learn how to design the UI…

  • Nic

    Hi!! Great tutorial.can you explain me how to create a series of playlist and pick one of them to play?

  • TunerX

    Thank You very much. Great help 🙂

  • danny

    hey ! great post but i was not able to login into your download section and download the code. because i never recieved the subscription confirmation email. please cehck . Thanks . Cheers ! 😀

  • jurds

    Hi Ravi,

    Thanks for this tutorial, I got it working. I have a concern though, the stack trace displays a lot of logs from the constant checking of getDuration and getCurrentPosition. If however someone uses this for a bigger application, I wanted to stop the checking after I’m done or stopped the media player. If someone has resolved this or will resolve this, please let me know. Thanks a lot.

  • Cheramis

    Where should you put this codes? I am new to android and so would appreciate the help. Thank you.

  • Cheramis

    Would you know where to add the codes stated by MarioB? I’m still learning and don’t know exactly what to look for. Thank you.

  • viraj

    Hey thanks for the great tutorial.I am just a noob and want to learn android programming.I have got a force close issue and i dont know how to deal with this so can anyone please help me out!!

  • viraj

    i got the same kind of problem.if you find any solution please let me know

  • nesseser

    rand.nextInt((songsList.size() – 1) – 0 + 1) + 0 What is it?

  • nesseser

    currentSongIndex = rand.nextInt((songsList.size() – 1) – 0 + 1) + 0;

    What is it?

  • jupiter.at

    Hi all. If I need timer to close this app. What is technique I should use???

  • jupiter.at

    I need to close this app with specific time. What is technique I should use?

  • tanhung

    thanks

  • matlab

    Thanks for Great Tutorial.
    i have 10 songs in raw folder . how can i show in a listview.
    all songs from raw folder in listview.

    please tell to me how change “playlist.java” for read songs from raw folder

  • matlab

    Edit…

    Thanks for Great Tutorial.
    i have 10 songs in raw folder . how can i show in a listview.
    all songs from raw folder in listview.

    please tell to me how change “SongsManager.java” for read songs from raw folder

  • ALRASHIDI

    HI Ravi

    How to change the path to link ( URL )

    final String MEDIA_PATH = new String(“/sdcard/”);

    • To fix error simply add final String MEDIA_PATH = new String(Environment.getExternalStorageDirectory().getPath() +”/sdcard/”);

      in song manger then create sdcard folder in your external storage and add songs in it install and tada!!!!!!!23

  • TrongDuy

    How to download a file mp3 throught a path link on internet in android.Please help me.

  • arpit

    hello, nice one working i want dowanload this code ? how if is it possible so plese send me link or option for download this audio player tutoriacl code

  • tolen

    Hi I want to ask you how to design next/back buttons to get list of items from data base please.

  • gndp

    MEDIA_PATH in SongsManager.java is set to “/sdcard/” which might not be the correct path.
    In my case I set it to “/storage/emlated/0/Music” and everything works fine.

    It plays the music as soon as it starts so incorrect path leads to Force Close

  • James

    Hey, how do you make it so that the program looks for all the MP3 files in the android device rather than in a directory?

  • Nido Serius

    Sir its very Good Tutorial, but When I stop the song and press the back button of the emulator the application Crashes every time. I Tried many times to correct it by using other methods but it continues Crashing on exit or back button?
    Kindly Help me

    • Abioye Samson

      mHandler.removeCallbacks(mUpdateTimeTask);

  • Nido Serius

    Crash Problem Solved.

    write this statement in onDestroy

    mHandler.removeCallbacks(mUpdateTimeTask);

    and your problem will be solve……
    if u want to thanks me, ping me on my email naveed_ahmad412@yahoo.com

    • To fix error simply add final String MEDIA_PATH = new String(Environment.getExternalStorageDirectory().getPath() +”/sdcard/”);

      in song manger then create sdcard folder in your external storage and add songs in it install and tada!!!!!!!456

      • Paul75

        Not solve form me …. Crash on start ….

        • try downloading fresh copy and apply this fix

          • Paul75

            I try to download again and remove the line playsong(0) and it crash again ..

          • you are getting error on emulator or phone (android)
            try phone for install.
            check if the error is same if it is same you must check version of phone if you have very high version some methods may be deprecated like in 4.4

          • Paul75

            Hello, I test in my Samsung Galaxy S3 with the version 4.3 Android.
            I have selve the problem in SongsManager : final String MEDIA_PATH = new String(Environment.getExternalStorageDirectory() +”/media/”); —-> NOT final String MEDIA_PATH = new String(“/sdcard/”); ….

            But now it works but sometimes the application crach …. not everytimes ….
            When I quit it….

          • If the player is working now means playing songs in your media folder then crashes when you close it with error unfortunately the media player is stopped working this error is because of the thread for the seek bar then you have to do this.

            Adding
            mHandler.removeCallbacks(mUpdateTimeTask);
            mHandler = null;
            in onDestroy solves the problem

          • Paul75

            Hello,

            Thanks solve the problem….

          • Williamz Nastrodumus Sanji

            dude ur awesome i tried to debug this for day and u just fixed it for me 🙂

        • remove the playsong(0);
          in main activity it won’t crash on start

  • MAdhav Anadkat

    Hey Ravi

    this is not working, its seems to force close so can u please help me to out this
    this also not work in real device to.

    thanks in advance.

  • ulyray

    Hi Danish, are you still active in this forum? I’ve downloaded the code. But when I tried to build it it says that I have to remove the @override notation on the click event and on the part of array list item. Is there something lacking on the code?

  • Krunal Doshi

    Change MEDIA_PATH to where music is placed in your device.

    example : final String MEDIA_PATH = new String(“/storage/emulated/0/Download/”);

  • Jomy P Jose

    add a music file (.mp3) into sdcard.

  • Đại Ngốc

    thanks for you.! great tutorial

  • Đại Ngốc

    i have question is, how do i can coppy data or music into sdcard, because, i coppy it’s message “incorrect format”

  • siraj

    u need to upload some mp3 musics in your sdcard. befor u starting to upload u need to give emulator about 1024MB spce and 512 MB RAM. when u did that upload push some mp3 music in your sdcard

  • Mike

    Thanks for this great tutorial but it doesn’t work…..on any device. Crashes every time I try to compile for hundreds of reasons.

  • Evans Mauta

    Awesome tutorial! I have a question though. How can I get songs to show in a “Title” – “Artist” – “Duration” format in the PlaylistActivity? Thanks in advance!

  • Romane

    To all those who have tried to make this Tutorial work without success.

    When i first tried this tutorial it didn’t work for me, I wasn’t testing on an emulator I was testing on my HTC mini.

    It has no “sdcard’ folder so every time i tried to run the app it crashed.

    I fixed it by creating a new folder on the phone called “sdcard” and putting audio in it. Then it worked great!

    The final issue I noticed was that if you turned the phone “Horizontal ” it would also crash.

    I don’t know how to fix these, but maybe someone could come up with the code to catch these issues.

    • arash ataafarin

      thanks man , Solved! In Samsung Phone if you did not insert sd card in your phone,you should create sdcard as Romane said and change the path in SongsManager.Java to /storage/emulated/0/sdcard/

  • Prashant

    Nice Tutorial !!!!!!

  • Hellmouth

    “currentSongIndex = rand.nextInt((songsList.size() – 1) – 0 + 1) + 0;”

    I am still trying to decipher why the hell did you add a zero and then subtract one.
    Also, limiting the rand to the range within the list but then adding one after it?

    The effect is the same as if you just did rand.nextInt without the “-1” inside… as far as I understand the process.

  • Hellmouth

    “if(mp.isPlaying()){
    if(mp!=null){”

    err WAT

    You call on mp’s method, and THEN you check if mp object is null?

  • James

    hi,

    iv downloaded all the code, no errors or warnings, my app appears on my huawei y300 , put once i try to open it, an error message comes up saying “appname” has stopped working?? should it not at least build and show the list view etc? is there something simple i am missing?

    plz help.

  • Khushwant Singh

    Hi,

    Simply the best.

    For those this app is crashing and in case they are running this sample directly on phone, please make sure that your phone is set to “Charge only” and NOT disk drive mode. In case your phone is connected in disk drive mode, the SD card will not be accessible by phone/app and app will crash.

    Thanks,
    Khushwant Singh

    • Thank for the tip Mr Khushwant 🙂

      • habib fall

        hello Ravi Tamada
        can you help me plez i got this error
        hope
        s04-19 15:24:14.839: D/AndroidRuntime(2565): Shutting down VM
        04-19 15:24:14.839: W/dalvikvm(2565): threadid=1: thread exiting with uncaught exception (group=0xb1d54b20)
        04-19 15:24:14.859: E/AndroidRuntime(2565): FATAL EXCEPTION: main
        04-19 15:24:14.859: E/AndroidRuntime(2565): Process: com.androidhive.musicplayer, PID: 2565
        04-19 15:24:14.859: E/AndroidRuntime(2565): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.musicplayer/com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity}: java.lang.NullPointerException
        04-19 15:24:14.859: E/AndroidRuntime(2565): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
        04-19 15:24:14.859: E/AndroidRuntime(2565): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
        04-19 15:24:14.859: E/AndroidRuntime(2565): at android.app.ActivityThread.access$800(ActivityThread.java:135)
        04-19 15:24:14.859: E/AndroidRuntime(2565): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
        04-19 15:24:14.859: E/AndroidRuntime(2565): at android.os.Handler.dispatchMessage(Handler.java:102)
        04-19 15:24:14.859: E/AndroidRuntime(2565): at android.os.Looper.loop(Looper.java:136)
        04-19 15:24:14.859: E/AndroidRuntime(2565): at android.app.ActivityThread.main(ActivityThread.java:5017)
        04-19 15:24:14.859: E/AndroidRuntime(2565): at java.lang.reflect.Method.invokeNative(Native Method)
        04-19 15:24:14.859: E/AndroidRuntime(2565): at java.lang.reflect.Method.invoke(Method.java:515)
        04-19 15:24:14.859: E/AndroidRuntime(2565): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
        04-19 15:24:14.859: E/AndroidRuntime(2565): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
        04-19 15:24:14.859: E/AndroidRuntime(2565): at dalvik.system.NativeStart.main(Native Method)
        04-19 15:24:14.859: E/AndroidRuntime(2565): Caused by: java.lang.NullPointerException
        04-19 15:24:14.859: E/AndroidRuntime(2565): at com.androidhive.musicplayer.SongsManager.getPlayList(SongsManager.java:29)
        04-19 15:24:14.859: E/AndroidRuntime(2565): at com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity.onCreate(AndroidBuildingMusicPlayerActivity.java:78)
        04-19 15:24:14.859: E/AndroidRuntime(2565): at android.app.Activity.performCreate(Activity.java:5231)
        04-19 15:24:14.859: E/AndroidRuntime(2565): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
        04-19 15:24:14.859: E/AndroidRuntime(2565): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
        04-19 15:24:14.859: E/AndroidRuntime(2565): … 11 more

  • Mony

    Hi, does anyone fixed the error which makes app get down? I am trying to make my own player according this tutorial, but still do not know what is wrong, Thanks for any advice

  • Anas Reza

    This tutorial is very good but can anyone help me that how to increase or decrease playback speed?

  • SinX

    Whenever I Click Playlist i get error and force stop. What can i do?

  • Everything is working correctly but there is only one thing I am having issue with. That is this code is unable to find music from all of the SD Card. It would be great help if someone could help me with it.

  • Đinh Phan Vũ Long

    share source code this post to me, please !

    dinhphanvu@gmail.com

  • Ahmad

    Hi Ravi, Please could you help me with play mutiple songs from res/raw folder? I really need it if you have time .. thanks in advance
    man 🙂

  • Naresh Maram

    i am also facing the same problem ,when i tested with real device it gives the “Unfortunatly music player has stoped”…

  • Naresh Maram

    i aslo faceing the same problem ,if you find the solution,please send to my mail id nareshmaram95@gmail.com

    Thanks

  • fikri jufri

    shared source code please!!
    fikrijufritham@gmail.com

  • Sylvina

    hi abhi,

    i’m new in android.

    Could tell me where is to put the”SD card root folder”. is it in the package inside of any folder or what,

    and can you explain me about:

    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)

    platform-tools> adb push “c:SongsWhite Flag.mp3” “/sdcard/”

    thank you

  • putracrishtyan

    When I try to download my browser doesn’t download the source code, can you please send me the source code please,thank you
    putracrishtyan1@gmail.com

  • Palak Mevada

    Helpful after completing the new boston series of android development and taking a step ahead in to droid stuffs….would be working on this from tomorrow,thanx a lot…

  • Anirudha

    mUpdateTimeTask is leaked, Just put a log in the run and you will see. Also pausing the current song and pressing back buttons make the application crash since onDestroy media player is released and calling getDuration on it results in IllegalStateException.

    • Anirudha

      Adding
      mHandler.removeCallbacks(mUpdateTimeTask);
      mHandler = null;
      in onDestroy solves the problem

      • Janice

        Thanks for your help! : )

        • Paul75

          Not for me …..

          • Anirudha

            Can you please elaborate ?

  • Mayur

    When This Source code run my AVD the Error generate like “Unfortuntly application stoped”
    How solve this error?
    give the solution plz…

    • SimpleMinds

      whats its solution???

  • ravikant

    hii ravi
    i got this error on my emulator “Unfortunately, AndroidBuilderMusicPlayer has stopped”
    Rly the solution Plz

    • Bob Smith

      It could be any number of reasons. Any crash in the java code can cause your app to stop. Look in your LogCat in Eclipse for red text. It will give you a call stack and help you find where the code is crashing.

      • Paul75

        For me :
        02-14 17:34:34.234: E/AndroidRuntime(31239): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.musicplayer/com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
        02-14 17:34:34.234: E/AndroidRuntime(31239): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295)
        02-14 17:34:34.234: E/AndroidRuntime(31239): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
        02-14 17:34:34.234: E/AndroidRuntime(31239): at android.app.ActivityThread.access$700(ActivityThread.java:159)
        02-14 17:34:34.234: E/AndroidRuntime(31239): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
        02-14 17:34:34.234: E/AndroidRuntime(31239): at android.os.Handler.dispatchMessage(Handler.java:99)
        02-14 17:34:34.234: E/AndroidRuntime(31239): at android.os.Looper.loop(Looper.java:176)
        02-14 17:34:34.234: E/AndroidRuntime(31239): at android.app.ActivityThread.main(ActivityThread.java:5419)
        02-14 17:34:34.234: E/AndroidRuntime(31239): at java.lang.reflect.Method.invokeNative(Native Method)
        02-14 17:34:34.234: E/AndroidRuntime(31239): at java.lang.reflect.Method.invoke(Method.java:525)
        02-14 17:34:34.234: E/AndroidRuntime(31239): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
        02-14 17:34:34.234: E/AndroidRuntime(31239): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
        02-14 17:34:34.234: E/AndroidRuntime(31239): at dalvik.system.NativeStart.main(Native Method)
        02-14 17:34:34.234: E/AndroidRuntime(31239): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
        02-14 17:34:34.234: E/AndroidRuntime(31239): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
        02-14 17:34:34.234: E/AndroidRuntime(31239): at java.util.ArrayList.get(ArrayList.java:308)
        02-14 17:34:34.234: E/AndroidRuntime(31239): at com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity.playSong(AndroidBuildingMusicPlayerActivity.java:281)
        02-14 17:34:34.234: E/AndroidRuntime(31239): at com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity.onCreate(AndroidBuildingMusicPlayerActivity.java:80)
        02-14 17:34:34.234: E/AndroidRuntime(31239): at android.app.Activity.performCreate(Activity.java:5372)
        02-14 17:34:34.234: E/AndroidRuntime(31239): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
        02-14 17:34:34.234: E/AndroidRuntime(31239): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
        02-14 17:34:34.234: E/AndroidRuntime(31239): … 11 more

        Why ?

        • Anirudha

          This error is occurring because when playsong(0) is called songsList is empty. Put a check in playsong method where you check “songIndex” is less than size of the songList ArrayList

          • Mayank Langalia

            Anirudha

            i have same problem please tell me. any help would be appreciated

  • Miguel Pakira

    hey people i am new in android app development… so, i wanna know what i need to develop this audio player…. i know, i need Eclipse or other but i wanna know the best IDE to use and this things, i am in a project and this prject is a audio player for my school… so help me please…. what i do? fast answer please… thanks

    • Bob Smith

      Eclipse is the best IDE in my opinion. Android even has a bundle that installs Eclipse completely ready to develop for android. Here’s a link: http://developer.android.com/sdk/index.html After you install the bundle, you just have to launch eclipse, create a new android application project and then you are ready to run.

  • Danny Herrera

    No he podido descargar el codigo fuente pero el tutorial muy bien

  • george

    Hi all. I am a novice in developing app and thanks to
    Ravi for all good work that is doing . I’m working at a simple app and I get
    stuck . if you have knowledge of
    building android apps, and make team
    with me please replay to george.celsie@gmail.com . Thanks ang
    good luck for all your projects.!

  • Paul75

    Hello,

    Thanks for player.
    I want to use it but in my program i create two buttons. In default the player is visibility gone and when I click to the first button I want to appear the player. and in the second button set the visibility VISIBLE. It works but when I start playing I want to stop the player. When I can do this ? Besause I use mp.stop() or mp.release(); but it crash or if I click to the first button it launch the player. …

    Thanks for help.

  • akbar88

    Hi,

    I’m really new to Android. I try your codes and got this error message “Unfortunately, AndroidBuilderMusicPlayer has stopped” on the emulator.
    On the console, it said ‘Failed to install AndroidBuildingMusicPlayer.apk on device ’emulator-5554!’

    Really need solution for my study.
    thanks a lot.

    • akbar88

      I also have tried the suggestions as mentioned on the previous comments. The app is successfully installed but still crash while being launched on the emulator. Any suggestions?

      • Paul

        same here… i downloaded and crash every time i run it :S

  • steve

    U can check it in storage area.click that storage area in emulator u can see all the mp3 files

  • nice … quite innovative!

  • Sandip Borad

    This is good.. but how can i find all song from artist or album name using http request…

  • Yaakov Shahak

    I tried to run the code on AVD but I got those crash:

    03-11 04:48:07.649: E/AndroidRuntime(2502): FATAL EXCEPTION: main

    03-11 04:48:07.649: E/AndroidRuntime(2502): Process: com.androidhive.musicplayer, PID: 2502

    03-11 04:48:07.649: E/AndroidRuntime(2502): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.musicplayer/com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity}: java.lang.NullPointerException

    03-11 04:48:07.649: E/AndroidRuntime(2502): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)

    03-11 04:48:07.649: E/AndroidRuntime(2502): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)

    03-11 04:48:07.649: E/AndroidRuntime(2502): at android.app.ActivityThread.access$800(ActivityThread.java:135)

    03-11 04:48:07.649: E/AndroidRuntime(2502): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)

    03-11 04:48:07.649: E/AndroidRuntime(2502): at android.os.Handler.dispatchMessage(Handler.java:102)

    03-11 04:48:07.649: E/AndroidRuntime(2502): at android.os.Looper.loop(Looper.java:136)

    03-11 04:48:07.649: E/AndroidRuntime(2502): at android.app.ActivityThread.main(ActivityThread.java:5017)

    03-11 04:48:07.649: E/AndroidRuntime(2502): at java.lang.reflect.Method.invokeNative(Native Method)

    03-11 04:48:07.649: E/AndroidRuntime(2502): at java.lang.reflect.Method.invoke(Method.java:515)

    03-11 04:48:07.649: E/AndroidRuntime(2502): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)

    03-11 04:48:07.649: E/AndroidRuntime(2502): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)

    03-11 04:48:07.649: E/AndroidRuntime(2502): at dalvik.system.NativeStart.main(Native Method)

    03-11 04:48:07.649: E/AndroidRuntime(2502): Caused by: java.lang.NullPointerException

    03-11 04:48:07.649: E/AndroidRuntime(2502): at com.androidhive.musicplayer.SongsManager.getPlayList(SongsManager.java:25)

    03-11 04:48:07.649: E/AndroidRuntime(2502): at com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity.onCreate(AndroidBuildingMusicPlayerActivity.java:77)

    03-11 04:48:07.649: E/AndroidRuntime(2502): at android.app.Activity.performCreate(Activity.java:5231)

    03-11 04:48:07.649: E/AndroidRuntime(2502): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)

    03-11 04:48:07.649: E/AndroidRuntime(2502): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)

    03-11 04:48:07.649: E/AndroidRuntime(2502): … 11 more

  • Tahir

    this player is not working if someone fix this error kindly help me out

  • Had the same issue going on guys. However, in my case I needed to get the mp3 files from the raw folder, not from the sdcard. If this is your case, on the getplaylist method from “SongsManager class” add the following:

    song.put(“songTitle”, “songname”);

    song.put(“songPath”, “android.resource://” + ActivityClass.PACKAGE_NAME + “/”+R.raw.file);

    (Of course do this per each file that you need)

    (Where: “songname” is the song’s name, the ActivityClass.PACKAGE_NAME is the name of the package and the “R.raw.file” is your mp3 raw file in the folder: “res/raw” if you don’t have one, create it and that’s it! )

    Also (and this goes in general not only for raw files reading) in your onDestroy() method add the following:

    @Override
    public void onDestroy(){

    super.onDestroy();
    mHandler.removeCallbacks(mUpdateTimeTask); //add this (very important! >_<)
    mp.release();
    finish();
    }

    Hope this helps a bit! 😛

    • Paul

      hi.
      can u send me your code?

    • Saniya Sharma

      I’ve tried this… but it does not work…can u send me ur code to my email id : saniyasharma455@yahoo.com

    • I as well have been trying this for about 3 days and cant seem to get it to work. I get *** ActivityClass cannot be resolved to a variable****

      I dont know exactly what Im doing wrong so any help would be greatly appreciated

      • Oh it’s because “activityclass” is the name of your activity! You have to change it depending on your activity name. Good luck!

        • song1.put(“songTitle”, “If I Never Make It”);

          song1.put(“songPath”, “android.resource://” + Music.com.officialloadedweaponsapp + “/”+R.raw.if_i_never_make_it);

          That is the line of code I believe I should have, but am still getting error stating

          “com cannot be resolved or is not a field SongsManager.java /OfficialLoadedWeaponsApp/src/com/officialloadedweaponsapp line 41 Java Problem”

          any Idea what I am not getting?

          • I assume your java class has the name: “Music”. So, try it like this: song1.put(“songPath”, “android.resource://” + Music.PACKAGE_NAME + “/”+R.raw.if_i_never_make_it);

            let me know!! 🙂 Forgot to tell you: Don’t change the “PACKAGE_NAME” variable with the name of your package, it automatically loads it 🙂

          • PACKAGE_NAME cannot be resolved or is not a field

            thats the error now.

            I tried to change it Music.class + “/”+R.raw.if_i_never_make_it);

            but that did nothing but load the xml layout.

          • Can you send me a print screen pic of your class structure? (java classes inside your package com.officialloadedweaponsapp) and a printscreen from your class Music? That will help a lot.. chavezlucero88@gmail.com is my email!

          • Thank you for all your help. I have emailed I hope what you were asking me to send lol

          • Mayank Langalia

            madam i have same problem please send me sample code
            mayanklangalia@gmail.com

  • Prafulla Malviya

    final String MEDIA_PATH = android.os.Environment.getExternalStorageDirectory().toString() + “/Download”;

    Change MEDIA PATH then it will work:
    For more query: call me @ facebook id :malviya.software@gmail.com

  • Saniya Sharma

    I want to add videos from raw folder on playlist instead from sdcard.. Can anyone suggest me how to do this….I tried dis :
    song.put(“songTitle”, “songname”);

    song.put(“songPath”, “android.resource://” +ActivityClass.PACKAGE_NAME + “/”+R.raw.file);

    but it doesn’t work..
    and another problem is that when I exit from music player it displays Unfortunately musicPlayer has been stopped…

  • Prashant

    Hi Ravi,

    I just want to say thank you for your all amazing tutorials on web. I find no better place on web to learn app development. Thanks A lot man.

  • Humayoon

    your code is not download i want to download plz any one help me

  • Humayoon

    plz tell when the song is playing i want to stop this song in navigation bar how could this any toturial plz help me

  • Thanks for the great start and effort you have provided us

    FATAL EXCEPTION: main

    Process: com.officialloadedweaponsapp, PID: 9922

    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.officialloadedweaponsapp/com.officialloadedweaponsapp.music}: java.lang.NullPointerException

    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java)

    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java)

    at android.app.ActivityThread.access$800(ActivityThread.java)

    at android.app.ActivityThread$H.handleMessage(ActivityThread.java)

    at android.os.Handler.dispatchMessage(Handler.java)

    at android.os.Looper.loop(Looper.java)

    at android.app.ActivityThread.main(ActivityThread.java)

    at java.lang.reflect.Method.invokeNative(Native Method)

    at java.lang.reflect.Method.invoke(Method.java)

    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)

    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)

    at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:133)

    at dalvik.system.NativeStart.main(Native Method)

    Caused by: java.lang.NullPointerException

    at com.officialloadedweaponsapp.SongsManager.getPlayList(SongsManager.java:25)

    at com.officialloadedweaponsapp.music.onCreate(music.java:78)

    at android.app.Activity.performCreate(Activity.java)

    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java)

    That is the error i get in the LogCat. very new to this and was wondering what I am doing wrong. Thanks for any help anyone can provide

    • It seems like the error is on the getplaylist method inside the songmanager class, check your media path that you are passing and it should work 🙂

      • Thank you for your quick reply, I will give it a try with any luck Ill be posting it worked haha

      • dheeraj

        but how can i find all song from artist or album name in media path mem

      • Yes !! Thank you ! that worked perfect. But I didnt quite understand your post about get song from raw folder. I couldnt get that to work. could you elaborate any more? Please ?!

        • Shahita Ahamed

          Hi.. I had the same error as yours and I’m not able to rectify it. Can you please let me know the changes that you’ve made? Thanks a lot for your help..

        • Mayank Langalia

          madam, i have same problem
          can you please tell me what changes that you have done
          i’m not able to rectify it

  • dheeraj

    Everything is working correctly but there is only one thing I am having issue with. That is this code is unable to find music from all of the SD Card. It would be great help if someone could help me with it. how to get All song our mobile……plzzzzzz

    • Юра Наливайко

      You need to use ContentResolver.

      Something like this:

      Cursor cursor = getContentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);

      And then:

      ArrayList arrayList;
      if (cursor.moveToFirst()) {
      do {
      arrayList.add(cursor.getString(1));
      } while (cursor.moveToNext());
      }

      Now your arrayList contains absolute paths to ALL songs on device.

  • Rose Caz

    Hello sir !
    what if i want to add / delete playlist… do you hav a tutorial for that?
    and i want to ADD some lyrics.. too

  • Shahita Ahamed

    Hi, Ravi and other fellow developers:
    Thank you so much for all your help. I’ve a small issue with the player. I want the code to read all the songs that are available in the device (both from internal memeory and SD card).. how do I do that? Please help. Thank you..

    (I’m new to android developing. Please tell me how to modify SongsManager.java such that it reads all songs from the device.. Thank you so much for the help)

    • dheeraj

      public class SongsManager {

      final String MEDIA_PATH = Environment.getExternalStorageDirectory()

      .getPath() + “/”;

      private ArrayList<HashMap> songsList = new ArrayList<HashMap>();

      private String mp3Pattern = “.mp3”;

      // Constructor

      public SongsManager() {

      }

      /**

      * Function to read all mp3 files and store the details in

      * ArrayList

      * */

      public ArrayList<HashMap> getPlayList() {

      System.out.println(MEDIA_PATH);

      if (MEDIA_PATH != null) {

      File home = new File(MEDIA_PATH);

      File[] listFiles = home.listFiles();

      if (listFiles != null && listFiles.length > 0) {

      for (File file : listFiles) {

      System.out.println(file.getAbsolutePath());

      if (file.isDirectory()) {

      scanDirectory(file);

      } else {

      addSongToList(file);

      }

      }

      }

      }

      // return songs list array

      return songsList;

      }

      private void scanDirectory(File directory) {

      if (directory != null) {

      File[] listFiles = directory.listFiles();

      if (listFiles != null && listFiles.length > 0) {

      for (File file : listFiles) {

      if (file.isDirectory()) {

      scanDirectory(file);

      } else {

      addSongToList(file);

      }

      }

      }

      }

      }

      private void addSongToList(File song) {

      if (song.getName().endsWith(mp3Pattern)) {

      HashMap songMap = new HashMap();

      songMap.put(“songTitle”,

      song.getName().substring(0, (song.getName().length() – 4)));

      songMap.put(“songPath”, song.getPath());

      // Adding each song to SongList

      songsList.add(songMap);

      }

      }

      • Shahita Ahamed

        Hi, Dheeraj! Thank you so much for the reply. I really appreciate your help..

        is this how the code should be?

        package com.androidhive.musicplayer;

        import java.io.File;

        import java.io.FilenameFilter;

        import java.util.ArrayList;

        import java.util.HashMap;

        import android.os.Environment;

        public class SongsManager {

        // SDCard Path

        final String MEDIA_PATH = new String(Environment.getExternalStorageDirectory().getPath() + “/”);

        private ArrayList<HashMap> songsList = new ArrayList<HashMap>();

        private String mp3Pattern = “.mp3”;

        // Constructor

        public SongsManager(){

        }

        /**

        * Function to read all mp3 files from sdcard

        * and store the details in ArrayList

        * */

        public ArrayList<HashMap> getPlayList(){

        if(MEDIA_PATH!=null){

        File home = new File(MEDIA_PATH);

        File[] listFiles = home.listFiles();

        if (listFiles != null && listFiles.length > 0) {

        for (File file : listFiles) {

        // System.out.println(file.getAbsolutePath());

        if (file.isDirectory()) {

        scanDirectory(file);

        } else {

        addSongToList(file);

        }

        }

        }

        }

        // return songs list array

        return songsList;

        }

        private void scanDirectory(File directory) {

        if (directory != null) {

        File[] listFiles = directory.listFiles();

        if (listFiles != null && listFiles.length > 0) {

        for (File file : listFiles) {

        if (file.isDirectory()) {

        scanDirectory(file);

        } else {

        addSongToList(file);

        }

        }

        }

        }

        }

        private void addSongToList(File song) {

        if (song.getName().endsWith(mp3Pattern)) {

        HashMap songMap = new HashMap();

        songMap.put(“songTitle”,

        song.getName().substring(0, (song.getName().length() – 4)));

        songMap.put(“songPath”, song.getPath());

        // Adding each song to SongList

        songsList.add(songMap);

        }

        }

        }

        also if this is how it should be, the following errors appear..

        FATAL EXCEPTION: main

        Process: com.androidhive.musicplayer, PID: 25416

        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.musicplayer/com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)

        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)

        at android.app.ActivityThread.access$800(ActivityThread.java:135)

        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)

        at android.os.Handler.dispatchMessage(Handler.java:102)

        at android.os.Looper.loop(Looper.java:136)

        at android.app.ActivityThread.main(ActivityThread.java:5017)

        at java.lang.reflect.Method.invokeNative(Native Method)

        at java.lang.reflect.Method.invoke(Method.java:515)

        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)

        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)

        at dalvik.system.NativeStart.main(Native Method)

        Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

        at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)

        at java.util.ArrayList.get(ArrayList.java:308)

        at com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity.playSong(AndroidBuildingMusicPlayerActivity.java:281)

        at com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity.onCreate(AndroidBuildingMusicPlayerActivity.java:80)

        at android.app.Activity.performCreate(Activity.java:5231)

        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)

        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)

        what could be the issue?

  • dheeraj

    how to set image in every mp3 song in this media player

    • Adarsh Ap

      For each and every mp3 you need to store the image in drawable folder and you need to call them in android:src.

  • Adarsh Ap

    How to make the player to read mp 3 files from the raw folder instead of from SD card.?

  • ThuNga

    Hello, I’ve tried this, but it does not work 🙁 can you send me ur code to my email address: tranthunga2603@gmail.com 🙂 thank you so much 😀

  • Guest

    05-16 02:20:05.474: E/AndroidRuntime(1403): FATAL EXCEPTION: main

    05-16 02:20:05.474: E/AndroidRuntime(1403): Process: com.androidhive.musicplayer, PID: 1403

    05-16 02:20:05.474: E/AndroidRuntime(1403): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.musicplayer/com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity}: java.lang.NullPointerException

    05-16 02:20:05.474: E/AndroidRuntime(1403): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at android.app.ActivityThread.access$800(ActivityThread.java:135)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at android.os.Handler.dispatchMessage(Handler.java:102)

    please help me
    i got error please see below

    05-16 02:20:05.474: E/AndroidRuntime(1403): at android.os.Looper.loop(Looper.java:136)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at android.app.ActivityThread.main(ActivityThread.java:5017)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at java.lang.reflect.Method.invokeNative(Native Method)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at java.lang.reflect.Method.invoke(Method.java:515)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at dalvik.system.NativeStart.main(Native Method)

    05-16 02:20:05.474: E/AndroidRuntime(1403): Caused by: java.lang.NullPointerException

    05-16 02:20:05.474: E/AndroidRuntime(1403): at com.androidhive.musicplayer.SongsManager.getPlayList(SongsManager.java:25)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity.onCreate(AndroidBuildingMusicPlayerActivity.java:77)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at android.app.Activity.performCreate(Activity.java:5231)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)

    05-16 02:20:05.474: E/AndroidRuntime(1403): … 11 more

    • Aritro01

      getting the same error and the app is force closing …have u found any solution??

  • Guest

    05-16 02:20:05.474: E/AndroidRuntime(1403): FATAL EXCEPTION: main

    05-16 02:20:05.474: E/AndroidRuntime(1403): Process: com.androidhive.musicplayer, PID: 1403

    05-16 02:20:05.474: E/AndroidRuntime(1403): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.musicplayer/com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity}: java.lang.NullPointerException

    05-16 02:20:05.474: E/AndroidRuntime(1403): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at android.app.ActivityThread.access$800(ActivityThread.java:135)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at android.os.Handler.dispatchMessage(Handler.java:102)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at android.os.Looper.loop(Looper.java:136)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at android.app.ActivityThread.main(ActivityThread.java:5017)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at java.lang.reflect.Method.invokeNative(Native Method)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at java.lang.reflect.Method.invoke(Method.java:515)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at dalvik.system.NativeStart.main(Native Method)

    05-16 02:20:05.474: E/AndroidRuntime(1403): Caused by: java.lang.NullPointerException

    05-16 02:20:05.474: E/AndroidRuntime(1403): at com.androidhive.musicplayer.SongsManager.getPlayList(SongsManager.java:25)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity.onCreate(AndroidBuildingMusicPlayerActivity.java:77)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at android.app.Activity.performCreate(Activity.java:5231)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)

    05-16 02:20:05.474: E/AndroidRuntime(1403): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)

    05-16 02:20:05.474: E/AndroidRuntime(1403): … 11 more

  • Z.A Khan

    Hi Ravi. My problem is .. In my media player app . it runs in background after pressing home or back .. it is working fine. but when i select another song while other is running .. Two songs are playing together ..how to get rid of this. i have used mp.release(); but no idea what’s my mistake .. Thanks in advance..

    • Guest

      can you please help me to solve my problem ?
      see below

      05-16 02:20:05.474: E/AndroidRuntime(1403): FATAL EXCEPTION: main

      05-16 02:20:05.474: E/AndroidRuntime(1403): Process: com.androidhive.musicplayer, PID: 1403

      05-16 02:20:05.474: E/AndroidRuntime(1403): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.musicplayer/com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity}: java.lang.NullPointerException

      05-16 02:20:05.474: E/AndroidRuntime(1403): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)

      05-16 02:20:05.474: E/AndroidRuntime(1403): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)

      05-16 02:20:05.474: E/AndroidRuntime(1403): at android.app.ActivityThread.access$800(ActivityThread.java:135)

      05-16 02:20:05.474: E/AndroidRuntime(1403): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)

      05-16 02:20:05.474: E/AndroidRuntime(1403): at android.os.Handler.dispatchMessage(Handler.java:102)

      05-16 02:20:05.474: E/AndroidRuntime(1403): at android.os.Looper.loop(Looper.java:136)

      05-16 02:20:05.474: E/AndroidRuntime(1403): at android.app.ActivityThread.main(ActivityThread.java:5017)

      05-16 02:20:05.474: E/AndroidRuntime(1403): at java.lang.reflect.Method.invokeNative(Native Method)

      05-16 02:20:05.474: E/AndroidRuntime(1403): at java.lang.reflect.Method.invoke(Method.java:515)

      05-16 02:20:05.474: E/AndroidRuntime(1403): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)

      05-16 02:20:05.474: E/AndroidRuntime(1403): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)

      05-16 02:20:05.474: E/AndroidRuntime(1403): at dalvik.system.NativeStart.main(Native Method)

      05-16 02:20:05.474: E/AndroidRuntime(1403): Caused by: java.lang.NullPointerException

      05-16 02:20:05.474: E/AndroidRuntime(1403): at com.androidhive.musicplayer.SongsManager.getPlayList(SongsManager.java:25)

      05-16 02:20:05.474: E/AndroidRuntime(1403): at com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity.onCreate(AndroidBuildingMusicPlayerActivity.java:77)

      05-16 02:20:05.474: E/AndroidRuntime(1403): at android.app.Activity.performCreate(Activity.java:5231)

      05-16 02:20:05.474: E/AndroidRuntime(1403): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)

      05-16 02:20:05.474: E/AndroidRuntime(1403): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)

      05-16 02:20:05.474: E/AndroidRuntime(1403): … 11 more

  • Mayank Langalia

    how to play songs from assets folder in android ?

    any help please let me know …

  • Manav Mittal

    How to make the player to read mp 3 files from the raw folder instead of from SD card.?

    • Hello Android

      Hi..Manav..I have d same question… did u find how to do that ??

  • Weslley Bispo

    Hello, I tried this but it does not work:

    (you can send me ur code to my e-mail: weslley.bispo13 @ gmail.com 🙂

    I’m from Brazil and I’m comesando to develop this new language thanks: D

  • shruti

    hello, This post is very helpful to me. but i have one confusion. why in the PlayListActivity you have used two different ArrayLists(songsList , songsListData ) ? can someone plz explain this to me ?

    public class PlayListActivity extends ListActivity {

    // Songs list

    public ArrayList<HashMap> songsList = new ArrayList<HashMap>();

    @Override

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.playlist);

    ArrayList<HashMap> songsListData = new ArrayList<HashMap>();

    SongsManager plm = new SongsManager();

    // get all songs from sdcard

    this.songsList = plm.getPlayList();

    // looping through playlist

    for (int i = 0; i < songsList.size(); i++) {

    // creating new HashMap

    HashMap song = songsList.get(i);

    // adding HashList to ArrayList

    songsListData.add(song);

    }

    // Adding menuItems to ListView

    ListAdapter adapter = new SimpleAdapter(this, songsListData,

    R.layout.playlist_item, new String[] { “songTitle” }, new int[] {

    R.id.songTitle });

    setListAdapter(adapter);

  • ToupetteMan

    C’est de la MERDE!!! Toupette

  • Esraa Mohamed

    you should make class called “CallReceiver”

    and copy this :

    public class CallReceiver extends BroadcastReceiver {

    TelephonyManager telManager;

    Context context;

    @Override

    public void onReceive(Context context, Intent intent) {

    this.context = context;

    telManager = (TelephonyManager) context

    .getSystemService(Context.TELEPHONY_SERVICE);

    telManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);

    }

    private final PhoneStateListener phoneListener = new PhoneStateListener() {

    @Override

    public void onCallStateChanged(int state, String incomingNumber) {

    try {

    switch (state) {

    case TelephonyManager.CALL_STATE_RINGING: {

    // PAUSE

    break;

    }

    case TelephonyManager.CALL_STATE_OFFHOOK: {

    break;

    }

    case TelephonyManager.CALL_STATE_IDLE: {

    // PLAY

    break;

    }

    default: {

    }

    }

    } catch (Exception ex) {

    }

    }

    };

    //———————————————–

    and then on main activity :

    // ———————————————————————————————

    PhoneStateListener phoneStateListener = new PhoneStateListener() {

    @Override

    public void onCallStateChanged(int state, String incomingNumber) {

    if (state == TelephonyManager.CALL_STATE_RINGING) {

    mp.pause();

    } else if (state == TelephonyManager.CALL_STATE_IDLE) {

    mp.start();

    } else if (state == TelephonyManager.CALL_STATE_OFFHOOK) {

    // A call is dialing, active or on hold

    }

    super.onCallStateChanged(state, incomingNumber);

    }

    };

    TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);

    if (mgr != null) {

    mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);

    }

    // ——————————————————————————————-

  • TheAndroidKing

    For me, the problem was the android application permissions. I past that on my manifest file:

  • Soumyadeep Sur

    Hi, Ravi
    This as an awesome tutorial for music player. It helps me very much. You have created this app for the SD Card, but if we want to download mp3 from the url so how can we do that features?
    I want like that, A website where different songs like 10 or 15, and the app will take those mp3 files from the internet. Thus that app will work like online streaming app. So Please help about that matter.

  • Joe

    Does the androidhive subscribe feature still work? I don’t get any emails for me to activate…

  • pratik

    tried this application its not working ,force closing ?
    can u send mail me this project on pgadekar86@gmail.com .

  • UEFI

    force closing!!please check and post again

  • vaan

    i’m running the app in my smartphone but doesn’t work
    “Unfortunately, music player has stopped” that the message apear when i run the app 🙁
    please, anyone can solve this? 🙁

    • Check the logcat for errors.

      • vaan

        i’m already fix the red sign in script…no red sign anymore. but still the same problem has apear in emulator/smartphone screen: “Unfortunately, music player has stopped” :'(

  • Shreyas

    I want to play music in background. I am using stream music. what should i do?

    • Mohammad Tanvirul Islam

      just play your media player by android service.

  • app

    can you write the code of the Activity class ? i suffer from bug in eclipse :/

    • Mohammad Tanvirul Islam

      your comments is not clear. please describe or mail me at my email tanvirul.cse.jkkniu@gmail.com . i need some one who worked with streaming music

  • 姿妤 林

    If I want to play audio from internet , How do I do?
    For Example,I use php upload mp3 file to my local ,so there are many mp3 files,
    But I want to click one mp3 file then play … that,I don’t know How to do?Please help me,
    Thank you.

  • deepak

    hi ravi, m facing this prob.

    plzz solve this issue.. mail me at “deepak.varshney35@gmail.com”
    asap
    07-03 23:39:51.034: E/AndroidRuntime(6446): FATAL EXCEPTION: main

    07-03 23:39:51.034: E/AndroidRuntime(6446): Process: com.deepak.audioplayer, PID: 6446

    07-03 23:39:51.034: E/AndroidRuntime(6446): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.deepak.audioplayer/com.deepak.audioplayer.AndroidBuildingMusicPlayerActivity}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

    07-03 23:39:51.034: E/AndroidRuntime(6446): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)

    07-03 23:39:51.034: E/AndroidRuntime(6446): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)

    07-03 23:39:51.034: E/AndroidRuntime(6446): at android.app.ActivityThread.access$800(ActivityThread.java:139)

    07-03 23:39:51.034: E/AndroidRuntime(6446): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)

    07-03 23:39:51.034: E/AndroidRuntime(6446): at android.os.Handler.dispatchMessage(Handler.java:102)

    07-03 23:39:51.034: E/AndroidRuntime(6446): at android.os.Looper.loop(Looper.java:136)

    07-03 23:39:51.034: E/AndroidRuntime(6446): at android.app.ActivityThread.main(ActivityThread.java:5102)

    07-03 23:39:51.034: E/AndroidRuntime(6446): at java.lang.reflect.Method.invoke(Native Method)

    07-03 23:39:51.034: E/AndroidRuntime(6446): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)

    07-03 23:39:51.034: E/AndroidRuntime(6446): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)

    07-03 23:39:51.034: E/AndroidRuntime(6446): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

    07-03 23:39:51.034: E/AndroidRuntime(6446): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)

    07-03 23:39:51.034: E/AndroidRuntime(6446): at java.util.ArrayList.get(ArrayList.java:308)

    07-03 23:39:51.034: E/AndroidRuntime(6446): at com.deepak.audioplayer.AndroidBuildingMusicPlayerActivity.playSong(AndroidBuildingMusicPlayerActivity.java:281)

    07-03 23:39:51.034: E/AndroidRuntime(6446): at com.deepak.audioplayer.AndroidBuildingMusicPlayerActivity.onCreate(AndroidBuildingMusicPlayerActivity.java:80)

    07-03 23:39:51.034: E/AndroidRuntime(6446): at android.app.Activity.performCreate(Activity.java:5248)

    07-03 23:39:51.034: E/AndroidRuntime(6446): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)

    07-03 23:39:51.034: E/AndroidRuntime(6446): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2173)

    07-03 23:39:51.034: E/AndroidRuntime(6446): … 9 more

  • Neelanjana BASU ROY

    Hi the tutorial provided here does not work …it shows music played=r has stopped…Please provide a solution!

  • Qadzealous

    i dont know what the problem seems to be but this code keeps crashing “Unfortunately AppName Has Stopped” no errors at all i tried the logcat to see whats wrong it keeps pointing to line 72 on MainActivity heres the code on the line 72 i dont seem to know whats wrong // Listeners

    songProgressBar.setOnSeekBarChangeListener(this); help me brother

    • Qadzealos

      heres the logcat message

      06-25 18:52:44.912: E/AndroidRuntime(1372): FATAL EXCEPTION: main

      06-25 18:52:44.912: E/AndroidRuntime(1372): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.foalmusicplayer/com.example.foalmusicplayer.MainActivity}: java.lang.NullPointerException

      06-25 18:52:44.912: E/AndroidRuntime(1372): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)

      06-25 18:52:44.912: E/AndroidRuntime(1372): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)

      06-25 18:52:44.912: E/AndroidRuntime(1372): at android.app.ActivityThread.access$600(ActivityThread.java:141)

      06-25 18:52:44.912: E/AndroidRuntime(1372): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)

      06-25 18:52:44.912: E/AndroidRuntime(1372): at android.os.Handler.dispatchMessage(Handler.java:99)

      06-25 18:52:44.912: E/AndroidRuntime(1372): at android.os.Looper.loop(Looper.java:137)

      06-25 18:52:44.912: E/AndroidRuntime(1372): at android.app.ActivityThread.main(ActivityThread.java:5039)

      06-25 18:52:44.912: E/AndroidRuntime(1372): at java.lang.reflect.Method.invokeNative(Native Method)

      06-25 18:52:44.912: E/AndroidRuntime(1372): at java.lang.reflect.Method.invoke(Method.java:511)

      06-25 18:52:44.912: E/AndroidRuntime(1372): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)

      06-25 18:52:44.912: E/AndroidRuntime(1372): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)

      06-25 18:52:44.912: E/AndroidRuntime(1372): at dalvik.system.NativeStart.main(Native Method)

      06-25 18:52:44.912: E/AndroidRuntime(1372): Caused by: java.lang.NullPointerException

      06-25 18:52:44.912: E/AndroidRuntime(1372): at com.example.foalmusicplayer.MainActivity.onCreate(MainActivity.java:72)

      06-25 18:52:44.912: E/AndroidRuntime(1372): at android.app.Activity.performCreate(Activity.java:5104)

      06-25 18:52:44.912: E/AndroidRuntime(1372): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)

      06-25 18:52:44.912: E/AndroidRuntime(1372): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)

      06-25 18:52:44.912: E/AndroidRuntime(1372): … 11 more

      • laxman

        i have same problem:(

  • saurabh

    App crashes on start. please help

    • Shohel

      Change your “MEDIA_PATH” name in SongManager class.Can not get any song.

      • abdul

        how to change path?
        please help me..

  • amy

    Hello~

    i want make podcast app with this code
    but i have a problem

    1. I have to call the parser using RSS but it doesn,t show Listview(i think PlayListActivity.java)

    2. i use emulator, An error has Logcat occurred. this error is next line.
    07-11 02:22:10.112: W/SurfaceFlinger(52): couldn’t log to binary event log: overflow.

    What should i do???
    please….

  • Hello android

    Hi.. I tried d above code..but it is showing me,error message in Utilities.java file.. does n e one knw hw 2 solve this issue ??

  • mk571app

    To play all sound in SDCARD, please insert this code
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public class SongsManager {

    // SDCard Path

    final String MEDIA_PATH = Environment.getExternalStorageDirectory()

    .getPath() + “/”;

    private ArrayList<HashMap> songsList = new ArrayList<HashMap>();

    private String mp3Pattern = “.mp3”;

    // Constructor

    public SongsManager() {

    }

    /**

    * Function to read all mp3 files and store the details in

    * ArrayList

    * */

    public ArrayList<HashMap> getPlayList() {

    System.out.println(MEDIA_PATH);

    if (MEDIA_PATH != null) {

    File home = new File(MEDIA_PATH);

    File[] listFiles = home.listFiles();

    if (listFiles != null && listFiles.length > 0) {

    for (File file : listFiles) {

    System.out.println(file.getAbsolutePath());

    if (file.isDirectory()) {

    scanDirectory(file);

    } else {

    addSongToList(file);

    }

    }

    }

    }

    // return songs list array

    return songsList;

    }

    private void scanDirectory(File directory) {

    if (directory != null) {

    File[] listFiles = directory.listFiles();

    if (listFiles != null && listFiles.length > 0) {

    for (File file : listFiles) {

    if (file.isDirectory()) {

    scanDirectory(file);

    } else {

    addSongToList(file);

    }

    }

    }

    }

    }

    private void addSongToList(File song) {

    if (song.getName().endsWith(mp3Pattern)) {

    HashMap songMap = new HashMap();

    songMap.put(“songTitle”,

    song.getName().substring(0, (song.getName().length() – 4)));

    songMap.put(“songPath”, song.getPath());

    // Adding each song to SongList

    songsList.add(songMap);

    }

    }

    /**

    * Class to filter files which are having .mp3 & .mp4 extension

    * */

    class FileExtensionFilter implements FilenameFilter {

    public boolean accept(File dir, String name) {

    return (name.endsWith(“.mp3”) || name.endsWith(“.MP4”));

    }

    }

    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  • angela

    how about search songs from sdcard? thanks

  • vidhin

    Hi , this tutorial really useful for me … I have a doubt I need to trim a audio file..
    for example I have a audio file with 5 MIn.. I want to trim the file 2min to 4min… and save to sdcard…

    thanks for advance….

  • Azhar Mohammed

    Hi..I am using this musicplayer as a part of my app. I have given (button)onclicklistener from homepage(activity) to musicplayer(activity). And a button in musicplayer to Homepage. When i click on the musicplayer button in homepage. the song starts playing and everything works fine. When i go to homepage through intent and click on the musicplayer button in homepage the old song which started before is playing and a new media player is created and a new song is playing along with that Musicplayer UI is updated to the new song . Multiple clicks in musicplayer button creates multiple songs playing together . I just want to resume only the first created intent music player and not want to replace mediaplayer with new one.I have referred several sites but cant fix this. can any one help me with this.
    Thanks in advance

    • FIRAT

      “unable to start activity componentinfo java.lang.nullpointerexception” my problem is

      What is the solution ?

  • FIRAT

    “unable to start activity componentinfo java.lang.nullpointerexception” my problem is

    What is the solution ??

  • Matthew

    Please someone HELP!

    08-20 20:38:30.005: E/MediaPlayer-JNI(18488): QCMediaPlayer mediaplayer NOT present

    08-20 20:38:30.025: D/MediaPlayer[JAVA](18488): broadcasting MEDIA_CHANGE_PLAYER_STATE : reset

    08-20 20:38:30.025: D/AndroidRuntime(18488): Shutting down VM

    08-20 20:38:30.025: W/dalvikvm(18488): threadid=1: thread exiting with uncaught exception (group=0x41dabe48)

    08-20 20:38:30.035: E/AndroidRuntime(18488): FATAL EXCEPTION: main

    08-20 20:38:30.035: E/AndroidRuntime(18488): Process: com.androidhive.musicplayer, PID: 18488

    08-20 20:38:30.035: E/AndroidRuntime(18488): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.musicplayer/com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

    08-20 20:38:30.035: E/AndroidRuntime(18488): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2202)

    08-20 20:38:30.035: E/AndroidRuntime(18488): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2252)

    08-20 20:38:30.035: E/AndroidRuntime(18488): at android.app.ActivityThread.access$800(ActivityThread.java:139)

    08-20 20:38:30.035: E/AndroidRuntime(18488): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)

    08-20 20:38:30.035: E/AndroidRuntime(18488): at android.os.Handler.dispatchMessage(Handler.java:102)

    08-20 20:38:30.035: E/AndroidRuntime(18488): at android.os.Looper.loop(Looper.java:136)

    08-20 20:38:30.035: E/AndroidRuntime(18488): at android.app.ActivityThread.main(ActivityThread.java:5103)

    08-20 20:38:30.035: E/AndroidRuntime(18488): at java.lang.reflect.Method.invokeNative(Native Method)

    08-20 20:38:30.035: E/AndroidRuntime(18488): at java.lang.reflect.Method.invoke(Method.java:515)

    08-20 20:38:30.035: E/AndroidRuntime(18488): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:788)

    08-20 20:38:30.035: E/AndroidRuntime(18488): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:604)

    08-20 20:38:30.035: E/AndroidRuntime(18488): at dalvik.system.NativeStart.main(Native Method)

    08-20 20:38:30.035: E/AndroidRuntime(18488): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

    08-20 20:38:30.035: E/AndroidRuntime(18488): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)

    08-20 20:38:30.035: E/AndroidRuntime(18488): at java.util.ArrayList.get(ArrayList.java:308)

    08-20 20:38:30.035: E/AndroidRuntime(18488): at com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity.playSong(AndroidBuildingMusicPlayerActivity.java:281)

    08-20 20:38:30.035: E/AndroidRuntime(18488): at com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity.onCreate(AndroidBuildingMusicPlayerActivity.java:80)

    08-20 20:38:30.035: E/AndroidRuntime(18488): at android.app.Activity.performCreate(Activity.java:5275)

    08-20 20:38:30.035: E/AndroidRuntime(18488): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)

    08-20 20:38:30.035: E/AndroidRuntime(18488): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2166)

  • Hem

    Please HELP!!

    This code is not working.. i am getting this error “Unfortunately app has stop working”

    LogCat:
    09-02 09:31:33.329:
    I/Choreographer(1021): Skipped 30 frames! The application may be doing
    too much work on its main thread.

    Console:

    [2014-08-31 19:55:25 – AndroidBuildingMusicPlayer] Dx
    trouble writing output: already prepared
    [2014-08-31 19:55:26 – AndroidBuildingMusicPlayer] ——————————
    [2014-08-31 19:55:26 – AndroidBuildingMusicPlayer] Android Launch!
    [2014-08-31 19:55:26 – AndroidBuildingMusicPlayer] adb is running normally.
    [2014-08-31 19:55:26 – AndroidBuildingMusicPlayer] Performing com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity activity launch
    [2014-08-31 19:55:26 – AndroidBuildingMusicPlayer] Automatic Target Mode: launching new emulator with compatible AVD ‘Test’
    [2014-08-31 19:55:26 – AndroidBuildingMusicPlayer] Launching a new emulator with Virtual Device ‘Test’
    [2014-08-31 19:56:39 – Emulator] Failed to create Context 0x3005
    [2014-08-31 19:56:39 – Emulator] could not get wglGetExtensionsStringARB
    [2014-08-31 19:56:39 – Emulator] could not get wglGetExtensionsStringARB
    [2014-08-31 19:56:39 – Emulator] could not get wglGetExtensionsStringARB
    [2014-08-31 19:56:39 – Emulator] could not get wglGetExtensionsStringARB
    [2014-08-31 19:56:39 – Emulator] could not get wglGetExtensionsStringARB
    [2014-08-31 19:56:39 – Emulator] emulator: WARNING: Could not initialize OpenglES emulation, using software renderer.
    [2014-08-31 19:56:39 – Emulator] could not get wglGetExtensionsStringARB
    [2014-08-31 19:56:39 – Emulator] could not get wglGetExtensionsStringARB
    [2014-08-31 19:56:39 – Emulator] could not get wglGetExtensionsStringARB
    [2014-08-31 19:56:39 – Emulator] Warning: No DNS servers found

    • samar

      Hi…here every thing is running on the main UI Thread…which is causing this error as it is taking long time to run the methods or loading the songs..instead you can start a service to do that and bind it to the activity so that you can avoid this issue….

  • abdul

    I am getting this error “Unfortunately app has stop working”

    LogCat:

    09-16 15:00:31.459: W/dalvikvm(283): threadid=1: thread exiting with uncaught exception (group=0x4001d800)

    09-16 15:00:31.489: E/AndroidRuntime(283): FATAL EXCEPTION: main

    09-16 15:00:31.489: E/AndroidRuntime(283): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.musicplayer/com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity}: java.lang.NullPointerException

    09-16 15:00:31.489: E/AndroidRuntime(283): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)

    09-16 15:00:31.489: E/AndroidRuntime(283): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)

    09-16 15:00:31.489: E/AndroidRuntime(283): at android.app.ActivityThread.access$2300(ActivityThread.java:125)

    09-16 15:00:31.489: E/AndroidRuntime(283): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)

    09-16 15:00:31.489: E/AndroidRuntime(283): at android.os.Handler.dispatchMessage(Handler.java:99)

    09-16 15:00:31.489: E/AndroidRuntime(283): at android.os.Looper.loop(Looper.java:123)

    09-16 15:00:31.489: E/AndroidRuntime(283): at android.app.ActivityThread.main(ActivityThread.java:4627)

    09-16 15:00:31.489: E/AndroidRuntime(283): at java.lang.reflect.Method.invokeNative(Native Method)

    09-16 15:00:31.489: E/AndroidRuntime(283): at java.lang.reflect.Method.invoke(Method.java:521)

    09-16 15:00:31.489: E/AndroidRuntime(283): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)

    09-16 15:00:31.489: E/AndroidRuntime(283): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)

    09-16 15:00:31.489: E/AndroidRuntime(283): at dalvik.system.NativeStart.main(Native Method)

    09-16 15:00:31.489: E/AndroidRuntime(283): Caused by: java.lang.NullPointerException

    09-16 15:00:31.489: E/AndroidRuntime(283): at com.androidhive.musicplayer.SongsManager.getPlayList(SongsManager.java:25)

    09-16 15:00:31.489: E/AndroidRuntime(283): at com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity.onCreate(AndroidBuildingMusicPlayerActivity.java:77)

    09-16 15:00:31.489: E/AndroidRuntime(283): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)

    09-16 15:00:31.489: E/AndroidRuntime(283): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)

    09-16 15:00:31.489: E/AndroidRuntime(283): … 11 more

    • Ankit

      Do not forget to add

      to your manifest file

  • cc

    I implemented this code, except I changed it to play music from R.raw instead of from the sdcard. But onCompletion is never being called, rendering the shuffle and repeat functionality useless. Thus you’re only able to play one song, then the user has to manually select the next song.

    Does anyone know what the problem could be? I set breakpoints in onCompletion, and it’s just never being called period.

    • abdul

      how did u run this code for R.raw will u please help me..

      • cc

        Well, I’m not actually reading from R.raw. I’ve got everything hard-coded. The reason for that is eventually I want to have it streaming from the internet, but I’m going to need to find a web server I can use that allows streaming to android devices. If I can’t get streaming from the internet working, I’m just gonna bundle the songs with the app in the R.raw folder, and have it hard-coded. Of course that takes up a lot of space on the user’s device, so I’ll have to include a lot less songs.

  • JB

    Hello
    does anyone know about which license this Audio Player is based on? I appreciate if anyone could help me…

  • Jhazzmine

    force close!! :'( i can’t run it.. can someone help me? newbie here..

    • Ramesh

      Give path Ex: /sdcard/Music/.

  • Ken

    it crashes when I run it on real device.

  • Ramesh

    It Works fine.Thank you

    • Naim

      Can You send me Source code kindly bro ?
      I face Many error in my code.I can not solve it.
      Email=naimcse131@gmail.com
      Thanks.

  • Anshdeep Singh

    can anybody tell me how to make the artists and albums activity which is present in other music players to play the songs of a selected album/artist??

  • 姿妤 林

    well…A little problem
    When I try to escape system,it’s will cause system crash…

  • evA

    I test this project on my phone and not work .. application crash .. i have android 4.1.1 JB on vodafone 875

  • KAUSHIK MUKHERJEE

    great tutorial….I am able to build video player also with the help of this tutorial…..Thanks !!!!! 🙂

    • Rayma Usman

      plz send me ur code plz i really need.plzzz

  • Timkraai

    it give the error: “has stopped”

    logcat gives Caused by: java.lang.NullPointerException

    at com.androidhive.musicplayer.SongsManager.getPlayList(SongsManager.java:25)

    at com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity.onCreate(AndroidBuildingMusicPlayerActivity.java:77)

    i did changed my path to my music folder i have a nexus 5 so the path is: “/storage/emulated/0/Music” and there is a song in there

  • Guest

    Sir I installed this app in my phone but it crashes whenever i m trying to launch it……………………why?????

  • Dawinder

    hiii…
    i have a problem while open audio player app.
    there is a null point exception at SongManager.getPlayList.

    i d’nt know how to solve this,
    please help….

  • Dawinder

    now after giving permission in manifest it again shows exception given below.

    Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
    how to solve it??

    • bianc0niglio

      maybe you have no mp3 files directly within the MEDIA_PATH defined in SongsManager.java.
      on my Samsung S4 I had to change it to ‘/storage/extSdCard/Music’ and I can (successfully) play only mp3 files located within the folder, subfolders are ignored.

  • banggarong

    im not have a problem at running application.. but a error when i close application.. why ?

  • damien

    Hi i search this player but where we can read music from url it’s posible ? thank for your reply

  • cpot23

    Nice tutorial, thanks!
    I’m wondering how to get the cover art of the currently played song since we have this nice cover art placeholder in the layout file.
    Does anyone have a suggestion how to get it?
    Thanks in advance!

    • Jatin

      use MediaMetadataRetreiver class with getEmbeddedPicture() method.. use the following code.

      MediaMetadataRetriever metaRetriver;
      byte[] art;

      metaRetriver = new MediaMetadataRetriever();
      metaRetriver.setDataSource(songsList.get(songIndex).get(“songPath”));
      try {
      art = metaRetriver.getEmbeddedPicture();
      Bitmap songImage = BitmapFactory
      .decodeByteArray(art, 0, art.length);

  • vasant

    I am creating application that load sequential mp3 files from URLs. As i try it with initialize next mp3 files on completion of first mp3 files, but the problem is that, when first files complete, player take time to prepare or initialize the next mp3 files, yes I know that is part of the media player,it will take time to Prepare(For prepare() it may be long And for prepareAsync() comparatively sort time).

    But , What i need that, when first mp3 files complete there playing, next mp3 files (From url) should not take time to prepare,as it should play without interrupt. I want to know , Is there way to attach next mp3 files for buffering while playing current mp3?, so we can playing it without interrupt.

    http://stackoverflow.com/questions/27103935/android-is-there-way-to-play-sequential-mp3-files-from-urls-without-interrupt

  • artist

    Maybe a tutorial how to sort songs by album or artist ? Because the list of just all songs on the devices is way too long …

  • Shashimith

    How to settle Media path problem moto g uses /sdcard/Music/, where as my Samsung S4 I had to change it to ‘/storage/extSdCard/Music’ and also use final String MEDIA_PATH = Environment.getExternalStorageDirectory().getPath() + “/”; as this i have read in comment , please specify a solution which would work on all the devices .And also app crashes on
    backpress how to handle that.

  • baskar

    can anyone tell me how to get the album cover in the Image view? Thanks in advance

  • Tim Kraai

    Retrieving the song doesn’t work. I get the first song every time. Is there a solution?

    • Tim Kraai

      Fixed it with a getIntExtra
      Intent mIntent = getIntent();
      int intValue = mIntent.getIntExtra(“songIndex”, 0)

      • viky08

        where to add this??

  • k2

    To prevent crash when press back button, change onDestroy method to:

    @Override
    public void onDestroy(){
    super.onDestroy();
    mp.release();
    mHandler.removeCallbacks(mUpdateTimeTask);
    }

    • abalta

      Thanks, there is no crash any more.

  • Naim

    i have a problem while open audio player app. Unfortunately Stopped
    i d’nt know how to solve this,..
    Plzz sent me code Email :naimuiu001@gmail.com That’s very helpfull for mee .

    Thanks

    • abalta

      Make sure you have .mp3 files on specified directory like “/sdcard/”

  • Paras Nath Chaudhary

    Can you write on “handling audio focus” with media apps?

  • gencoder1

    Is there an way to incorporate notification control for the application to pause play etc…….. or if there are any tutorial similar to this one, great tut bTW..

  • silistre

    hi thank you very very much for tutorial but I can’t make “delete mp3 button” in playlist , How I can add delete mp3 button ? thanks for help

  • ullas

    hi was this code working In your devices people….?

    • abalta

      Yes it works great.

      • Guest

        can you send me this code kindly ..
        I face some trouble and more error this code..
        can not solve it.
        Email=naimuiucse131@gmail.com
        Thanks.

        • Rayma Usman

          please also send me this code please

      • Naim

        Can You send me Source code kindly ?
        I face Many error in my code.I can not solve it.
        Email=naimcse131@gmail.com
        Thanks.

  • vivek

    Really great code is working fine…

    • Rayma Usman

      please send me your code

    • Ahsan Misbah

      please send me your code, as i have a problem to launch this app.

    • Selva Kumar

      Hi Vivek,

      could you please send your working code? I’m getting plenty of errors when I opened in Android Visual Studio, and this is my first project,and also I’m in a hurry, kindly help.
      email: Kumar.selva.c@gmail.com

      Thanks

  • Ken

    Cannot download source code

  • Asile

    What if I want to make it read also other types of audio files? Like .m4a, .aac, .wma …

  • Priyank

    Thanks. its great tutorial…but i want back button , how to use service in this code

  • satyenhacks

    It crashed when I tested on my phone. I also added permission to read external storage but no use. What am I missing here?

    • Check the LogCat for errors.

      • Ambreen Khan

        How can I use this Player with parse.com, Can you suggest me any think? Means load files (Song URLs / Songs Titles audio/video) from parse.com database?
        If Possible
        Please Massage me on https://www.facebook.com/ambreen.khan.3304

  • Denis Marinx

    Now it works ! I had the error about the NullPointerException in getPlayList() so I replaced : “new File(MEDIA_PATH)” by “Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)” and add in AndroidManifest.xml file : Hope it helps ! Works on my device now 🙂

    • Denis Marinx

      I forgot to say thanks for this tutorial ! I’m beginning Android since a few days and it’s really easy to understand basics concepts. Some code will be changed because some bugs appear for me, anyway it will be a good exercice :). PS : You can add this additional feature for btnPrevious.setOnClickListener : if(mp.getCurrentPosition() > 15000){playSong(currentSongIndex);} // usually used

      • Rayma Usman

        plz can u send me ur code plz.i really need this code which run properly.plz can u help me plz

  • shahin

    Hello dear
    Thank you very much for your education.
    I have a button in my activity. Through this button I want to go to a music player activity. After pressing the button the forcclosed.
    Below you can see a picture of it.
    I am in a hurry. I appreciate your help.

    http://8pic.ir/images/8uxybnzpng9gh4gelyrb.png

  • a

    Import your application file in eclipse, but I did not run the program. In the photo below you can see the logcat messages. THX

    http://www.axgig.com/images/72515890951732908002.png

    • Rajkumar Savu

      please put a condition in AndroidBuildingMusicPlayerActivity class and method playSong(int songIndex) as songList.size()>0{
      }
      then it will work

  • sali

    Hi there
    Well, sorry, I can not speak the language designed for.
    It’s fine, I do not want to go play songs from Sdkard. I called the folder named Res raw in the world.
    I am very busy.
    Please help me get faster through e-mail me to do.

  • Gee

    Hi Ravi, is there a method to layer 2 mp3 sounds? I have been googling but i can find answers. I hope you can help. thank you so much and more power to your blog.

  • Atmiya Patel

    *****i m having this error please help*******

    03-09 14:29:26.989 23989-23989/com.mycompany.androidbuildingmusicplayer E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mycompany.androidbuildingmusicplayer/com.mycompany.androidbuildingmusicplayer.AndroidBuildingMusicPlayerActivity}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
    at android.app.ActivityThread.access$1500(ActivityThread.java:117)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:130)
    at android.app.ActivityThread.main(ActivityThread.java:3683)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:507)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:875)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
    at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
    at java.util.ArrayList.get(ArrayList.java:311)
    at com.mycompany.androidbuildingmusicplayer.AndroidBuildingMusicPlayerActivity.playSong(AndroidBuildingMusicPlayerActivity.java:281)
    at com.mycompany.androidbuildingmusicplayer.AndroidBuildingMusicPlayerActivity.onCreate(AndroidBuildingMusicPlayerActivity.java:80)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
    at android.app.ActivityThread.access$1500(ActivityThread.java:117)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:130)
    at android.app.ActivityThread.main(ActivityThread.java:3683)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:507)

  • Manivel

    Hi,

    can’t get started.. Its force closed. the path “/sdcard/” only i gave. and while run the cmd ‘platform-tools> adb push “c:Songs1.mp3” “/sdcard/”‘ it show the error is.. ‘Read only access’ like that. so am not able to run can you plz help me to common path for all the device.. am using AVD and device too..

    Logcat error i gues “file or directory is missing” something

  • raman kumar

    i Need Method To get Song Info Like Song Artist,album,Thumbnail … Please upload These Methods also .. I would Be Thankful To You!!

    • Vincent Tirgei

      Did you find a method?

      Please share if so

  • ankit gajjar

    Hello,

    I want to integrate only One Song to this music which is playing continuously.That song is in the android project assests folder. How can i play that song. give me advice.

  • Rayma Usman

    i have problem my my app run properly but when open it in my tab its giving me error unfortunately media player stop working.where’s the problem is anyone tell me please..

    • add to your manifest

      SongsManager change

      final String MEDIA_PATH = Environment.getExternalStorageDirectory().getPath()+ “/”;

      finally add some mp3 files in the internal storage of your phone…………………….sdcard is not necessary

      • Rayma Usman

        i do all these steps but problem is same.please help me seriously i really need

      • Rayma Usman

        thank u so much.i slove my problem thanks again 🙂

        • Where can download the source?
          Thanks

      • Mahfuz Ahmed

        Can you please show your manifest file?

        • Where can get the source..

          Thanks

      • Ahsan Misbah

        Hi
        dear i did this but app does not launch, every time it shows Unfortunately, MusicPlayer has stoped

    • tohin

      thanks Rayma usman, i solve my problem

  • Manikandan Thivager

    i am not able to download the source code…can u pls help me with that

  • Excelent code …………………………I am tryng the same functionality…….but without showing the Media Player………………..any idea is welcome…just. playing directly from the list………..

  • Jake Halawi

    “Attemp to call getduration without a valid mediaplayer(-38, 0) ” Help please.

  • Sudarshan Mondal

    I am getting the error on my log Cat

    04-09 10:23:42.971: E/AndroidRuntime(2378): FATAL EXCEPTION: main

    04-09 10:23:42.971: E/AndroidRuntime(2378): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.musicplayer/com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

    04-09 10:23:42.971: E/AndroidRuntime(2378): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)

    04-09 10:23:42.971: E/AndroidRuntime(2378): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)

    04-09 10:23:42.971: E/AndroidRuntime(2378): at android.app.ActivityThread.access$600(ActivityThread.java:141)

    04-09 10:23:42.971: E/AndroidRuntime(2378): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)

    04-09 10:23:42.971: E/AndroidRuntime(2378): at android.os.Handler.dispatchMessage(Handler.java:99)

    04-09 10:23:42.971: E/AndroidRuntime(2378): at android.os.Looper.loop(Looper.java:137)

    04-09 10:23:42.971: E/AndroidRuntime(2378): at android.app.ActivityThread.main(ActivityThread.java:5103)

    04-09 10:23:42.971: E/AndroidRuntime(2378): at java.lang.reflect.Method.invokeNative(Native Method)

    04-09 10:23:42.971: E/AndroidRuntime(2378): at java.lang.reflect.Method.invoke(Method.java:525)

    04-09 10:23:42.971: E/AndroidRuntime(2378): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)

    04-09 10:23:42.971: E/AndroidRuntime(2378): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)

    04-09 10:23:42.971: E/AndroidRuntime(2378): at dalvik.system.NativeStart.main(Native Method)

    04-09 10:23:42.971: E/AndroidRuntime(2378): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

    04-09 10:23:42.971: E/AndroidRuntime(2378): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)

    04-09 10:23:42.971: E/AndroidRuntime(2378): at java.util.ArrayList.get(ArrayList.java:308)

    04-09 10:23:42.971: E/AndroidRuntime(2378): at com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity.playSong(AndroidBuildingMusicPlayerActivity.java:281)

    04-09 10:23:42.971: E/AndroidRuntime(2378): at com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity.onCreate(AndroidBuildingMusicPlayerActivity.java:80)

    04-09 10:23:42.971: E/AndroidRuntime(2378): at android.app.Activity.performCreate(Activity.java:5133)

    04-09 10:23:42.971: E/AndroidRuntime(2378): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)

    04-09 10:23:42.971: E/AndroidRuntime(2378): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)

    04-09 10:23:42.971: E/AndroidRuntime(2378): … 11 more

    What should I do?

    • Rio

      you may need to stop Handler function at onDestroy(); function. just add mHandler.removeCallbacks(mUpdateTimeTask); at onDestroy(); hope this work.

    • murali dhar Yerram

      iam also getting same error did got of that prob…plz help me

  • Mcode

    this code absolutely not working…i tried everything…even alter the code on update suggestions….

    🙁

  • Vincent Kyalo

    I imported the source code to my eclipse but got the following error on my log Cat:

    04-20 21:03:35.603: E/AndroidRuntime(24908): FATAL EXCEPTION: main

    04-20 21:03:35.603: E/AndroidRuntime(24908): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.musicplayer/com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

    04-20 21:03:35.603: E/AndroidRuntime(24908): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2255)

    04-20 21:03:35.603: E/AndroidRuntime(24908): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2309)

    04-20 21:03:35.603: E/AndroidRuntime(24908): at android.app.ActivityThread.access$700(ActivityThread.java:157)

    04-20 21:03:35.603: E/AndroidRuntime(24908): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1289)

    04-20 21:03:35.603: E/AndroidRuntime(24908): at android.os.Handler.dispatchMessage(Handler.java:99)

    04-20 21:03:35.603: E/AndroidRuntime(24908): at android.os.Looper.loop(Looper.java:176)

    04-20 21:03:35.603: E/AndroidRuntime(24908): at android.app.ActivityThread.main(ActivityThread.java:5317)

    04-20 21:03:35.603: E/AndroidRuntime(24908): at java.lang.reflect.Method.invokeNative(Native Method)

    04-20 21:03:35.603: E/AndroidRuntime(24908): at java.lang.reflect.Method.invoke(Method.java:511)

    04-20 21:03:35.603: E/AndroidRuntime(24908): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)

    04-20 21:03:35.603: E/AndroidRuntime(24908): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)

    04-20 21:03:35.603: E/AndroidRuntime(24908): at dalvik.system.NativeStart.main(Native Method)

    04-20 21:03:35.603: E/AndroidRuntime(24908): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

    04-20 21:03:35.603: E/AndroidRuntime(24908): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)

    04-20 21:03:35.603: E/AndroidRuntime(24908): at java.util.ArrayList.get(ArrayList.java:304)

    04-20 21:03:35.603: E/AndroidRuntime(24908): at com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity.playSong(AndroidBuildingMusicPlayerActivity.java:281)

    04-20 21:03:35.603: E/AndroidRuntime(24908): at com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity.onCreate(AndroidBuildingMusicPlayerActivity.java:80)

    04-20 21:03:35.603: E/AndroidRuntime(24908): at android.app.Activity.performCreate(Activity.java:5326)

    04-20 21:03:35.603: E/AndroidRuntime(24908): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)

    04-20 21:03:35.603: E/AndroidRuntime(24908): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2218)

    04-20 21:03:35.603: E/AndroidRuntime(24908): … 11 more

    Please help me out

  • Ahsan Misbah

    I have a problem in my app, when ever i launch the app it says Unfortunately, MusicPlayer has stopped.
    Please help me to overcome this.
    No logcat errors i have.

    • Ahsan Misbah

      got this one in notification panel of android studio..

      Launching application: com.example.ahsan.musicplayer/com.example.ahsan.musicplayer.AndroidBuildingMusicPlayerActivity.

      DEVICE SHELL COMMAND: am start -n “com.example.ahsan.musicplayer/com.example.ahsan.musicplayer.AndroidBuildingMusicPlayerActivity” -a android.intent.action.MAIN -c android.intent.category.LAUNCHER

      Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.example.ahsan.musicplayer/.AndroidBuildingMusicPlayerActivity }

  • andro

    I am not able to access my external memory mp3 files , but its showing internal memory files. i m using my samsung galaxy s4 as the debugger.

    • kartik

      I am facing same problem with moto e
      even after using Environment.getExternalStorageDirectory.getAbsolutePath()/.getPath()
      and is even Showing MOUNTED as its status

      please help

  • Kadam Priyanka

    I have a same problem,when I launch the app it shows unfortunately music player has stopped.please help me.

    • rAyMa uSmAn

      change ur path.go to song manger.and set the path that is ur device path.

      • Tabrez Qureshi

        bru i tried all my device path bt it still shows unfortunately music player has stopped..

        • rAyMa uSmAn

          add to your manifest

          after this add ur right path in this line

          final String MEDIA_PATH = new String(“/sdcard/Music”);

          my device path is /sdcard/Music add ur right path with right spelling

  • gourav

    The app Crashes at back press, due to Runnable method…. have any solution 4 this???

  • kartik

    Hy Ravi Tamada thank u very much for explation and code

    but app is using only internal storage and not accessing SD card .i have chaged manifest file and also used Environment.getExternalStorageDirectory.getAbsolutePath()/.getPath() but its not working .and by status its showing MOUNTED .

    Please help

  • rAyMa uSmAn

    plz anyone give me ER diagram and class diagram of this media player..

  • rAyMa uSmAn

    by using this media player i done to design video player also.thank u so much…:)

  • Rajesh Battala

    Thanks for the write up. It helped

  • Nilesh Giradkar

    Code is not running… please mail me running code.. @ nileshgiradkar1@gmail.com

  • Nidhin Kumar

    How to do the same with streaming music using json instead of reading from sd card

  • Engedasew

    how to change sd-card media path into res/raw all codes related to that . . .

  • NSB

    Thank you very much for the tutorial. I made my own version out of it 🙂 using Android Studio

    Here is my code at paste.bin

    1- Main Activity :http://pastebin.com/ZJYr0Upj

    2- Player Activity: http://pastebin.com/wP6bAj5K

    The whole project is uploaded here : http://www.filedropper.com/basicmusicplayer

    • Patricia Mai Yuki Pedro

      your uploaded project link is not working always shows the homepage of that site

    • Selva Kumar

      Bro,could you please upload the working code.

  • DHAVAL

    Thanks for tutorial . but now days i am faceing one issue that occur only lolipop version. In my app i have 10 song and when i tap to next button or pervious button click whenever song is playing that time onCompletelistener oncompletemethod fire more then 5 or 6 time and song autometically play one by one automatically . step for getting this issue click on start play song button and and tap next button befor song starting time less then 10 second that time autometically 3 or 4 song goes away.

  • akn

    I manage to work this code

    1.Add “AndroidManifest.xml” this permision(it should be between “android:versionName=”1.0″ >:” to )

    2.Go “SongsManager.java” change:

    final String MEDIA_PATH = new Environment().getExternalStorageDirectory().getPath();

    3.Run code and go “Android Device Monitor” (it is near run button in Android Studio ) wait little bit then find
    “File Explorer” tab

    4.go mnt->sdcard then select this .Now you should add .mp3 file to do that look above
    there is a button “push a file onto the device” click this then choose your .mp3 file.

    5.if step 4 gives error , it is about permission find sdcard with d–rwxr-x permission
    it can be under stroge forder or only sdcard folder.In correct sdcard there is a thing called
    LOST.DIR
    or watch this video https://www.youtube.com/watch?v=ipRke1P4rIc

  • hardik

    i downloaded full source code but i am getting run time error on it. unfortunately all has stop working please any one tell me soiution for it..

  • Hetuka

    this code is very helpful for me, thanks a lot, now i want to add those songs in playlist and add to favorite please give a any solution,,,Thanks in Advance.

  • Namrata

    hi! this is just a minor issue but its still a bit of a nagger. The player.xml and playlist.xml files have the layout_width and layout_height set to “match_parent” and the compiler is taking it as an error. What can i replace it with? Thanks in advance. The rest is flawless.

  • Mohammad Akbari

    Thank you for this guide. :))

  • Sir when ever i run your music player there are many error showing up on the error log the error log in below:

    07-30 09:54:58.828: E/AndroidRuntime(15304): FATAL EXCEPTION: main

    07-30 09:54:58.828: E/AndroidRuntime(15304): Process: com.androidhive.musicplayer, PID: 15304

    07-30 09:54:58.828: E/AndroidRuntime(15304): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.musicplayer/com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity}: java.lang.NullPointerException: Attempt to get length of null array

    07-30 09:54:58.828: E/AndroidRuntime(15304): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2693)

    07-30 09:54:58.828: E/AndroidRuntime(15304): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)

    07-30 09:54:58.828: E/AndroidRuntime(15304): at android.app.ActivityThread.access$900(ActivityThread.java:177)

    07-30 09:54:58.828: E/AndroidRuntime(15304): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)

    07-30 09:54:58.828: E/AndroidRuntime(15304): at android.os.Handler.dispatchMessage(Handler.java:102)

    07-30 09:54:58.828: E/AndroidRuntime(15304): at android.os.Looper.loop(Looper.java:145)

    07-30 09:54:58.828: E/AndroidRuntime(15304): at android.app.ActivityThread.main(ActivityThread.java:5942)

    07-30 09:54:58.828: E/AndroidRuntime(15304): at java.lang.reflect.Method.invoke(Native Method)

    07-30 09:54:58.828: E/AndroidRuntime(15304): at java.lang.reflect.Method.invoke(Method.java:372)

    07-30 09:54:58.828: E/AndroidRuntime(15304): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)

    07-30 09:54:58.828: E/AndroidRuntime(15304): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)

    07-30 09:54:58.828: E/AndroidRuntime(15304): Caused by: java.lang.NullPointerException: Attempt to get length of null array

    07-30 09:54:58.828: E/AndroidRuntime(15304): at com.androidhive.musicplayer.SongsManager.getPlayList(SongsManager.java:22)

    07-30 09:54:58.828: E/AndroidRuntime(15304): at com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity.onCreate(AndroidBuildingMusicPlayerActivity.java:77)

    07-30 09:54:58.828: E/AndroidRuntime(15304): at android.app.Activity.performCreate(Activity.java:6283)

    07-30 09:54:58.828: E/AndroidRuntime(15304): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)

    07-30 09:54:58.828: E/AndroidRuntime(15304): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)

    07-30 09:54:58.828: E/AndroidRuntime(15304): … 10 more

    Can you please help me out in this

    • Prem K

      Hi Danish,

      Even i faced the same problem but it got resolved after adding permission for accessing storage in AndroidManifest.xml file.

      here is the snippet FYI

      • Suzan Maka

        bro i just got the same problem and i used your solution but it doesn’t work :/

  • Anuj Bhavsar

    i just add up your source code to Eclipse but emulator says app Unfortunately Stopped

    logCat:

    08-02 04:24:05.337: D/dalvikvm(573): Not late-enabling CheckJNI (already on)

    08-02 04:24:05.497: I/dalvikvm(573): Turning on JNI app bug workarounds for target SDK version 8…

    08-02 04:24:06.027: I/dalvikvm(573): threadid=3: reacting to signal 3

    08-02 04:24:06.143: I/dalvikvm(573): Wrote stack traces to ‘/data/anr/traces.txt’

    08-02 04:24:06.427: D/dalvikvm(573): GC_FOR_ALLOC freed 91K, 5% free 5613K/5891K, paused 51ms

    08-02 04:24:06.557: I/dalvikvm(573): threadid=3: reacting to signal 3

    08-02 04:24:06.607: I/dalvikvm(573): Wrote stack traces to ‘/data/anr/traces.txt’

    08-02 04:24:06.659: D/dalvikvm(573): GC_CONCURRENT freed 375K, 9% free 5741K/6279K, paused 6ms+4ms

    08-02 04:24:06.887: D/AndroidRuntime(573): Shutting down VM

    08-02 04:24:06.897: W/dalvikvm(573): threadid=1: thread exiting with uncaught exception (group=0x409bf1f8)

    08-02 04:24:06.917: E/AndroidRuntime(573): FATAL EXCEPTION: main

    08-02 04:24:06.917: E/AndroidRuntime(573): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.musicplayer/com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

    08-02 04:24:06.917: E/AndroidRuntime(573): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)

    08-02 04:24:06.917: E/AndroidRuntime(573): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)

    08-02 04:24:06.917: E/AndroidRuntime(573): at android.app.ActivityThread.access$600(ActivityThread.java:123)

    08-02 04:24:06.917: E/AndroidRuntime(573): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)

    08-02 04:24:06.917: E/AndroidRuntime(573): at android.os.Handler.dispatchMessage(Handler.java:99)

    08-02 04:24:06.917: E/AndroidRuntime(573): at android.os.Looper.loop(Looper.java:137)

    08-02 04:24:06.917: E/AndroidRuntime(573): at android.app.ActivityThread.main(ActivityThread.java:4424)

    08-02 04:24:06.917: E/AndroidRuntime(573): at java.lang.reflect.Method.invokeNative(Native Method)

    08-02 04:24:06.917: E/AndroidRuntime(573): at java.lang.reflect.Method.invoke(Method.java:511)

    08-02 04:24:06.917: E/AndroidRuntime(573): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)

    08-02 04:24:06.917: E/AndroidRuntime(573): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)

    08-02 04:24:06.917: E/AndroidRuntime(573): at dalvik.system.NativeStart.main(Native Method)

    08-02 04:24:06.917: E/AndroidRuntime(573): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

    08-02 04:24:06.917: E/AndroidRuntime(573): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)

    08-02 04:24:06.917: E/AndroidRuntime(573): at java.util.ArrayList.get(ArrayList.java:304)

    08-02 04:24:06.917: E/AndroidRuntime(573): at com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity.playSong(AndroidBuildingMusicPlayerActivity.java:281)

    08-02 04:24:06.917: E/AndroidRuntime(573): at com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity.onCreate(AndroidBuildingMusicPlayerActivity.java:80)

    08-02 04:24:06.917: E/AndroidRuntime(573): at android.app.Activity.performCreate(Activity.java:4466)

    08-02 04:24:06.917: E/AndroidRuntime(573): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)

    08-02 04:24:06.917: E/AndroidRuntime(573): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)

    08-02 04:24:06.917: E/AndroidRuntime(573): … 11 more

    08-02 04:24:07.037: D/dalvikvm(573): GC_CONCURRENT freed 391K, 9% free 5879K/6407K, paused 3ms+56ms

    08-02 04:24:07.132: I/dalvikvm(573): threadid=3: reacting to signal 3

    08-02 04:24:07.137: I/dalvikvm(573): Wrote stack traces to ‘/data/anr/traces.txt’

    08-02 04:24:07.516: I/dalvikvm(573): threadid=3: reacting to signal 3

    08-02 04:24:07.526: I/dalvikvm(573): Wrote stack traces to ‘/data/anr/traces.txt’

    • Dharmesh Garod

      You can email me Mr Bhavsar.
      I’ll Help You 😉

  • Prem K

    Thanks for the Tutorial dude!!!. It really helped me alot 🙂
    But i am facing a problem,Whenever i try to close the app, the media player is getting stopped.Ideally it has to play songs in the background, but its not happening.

  • Mike Frost Charvez

    wowwwwwwwww

  • Mohammad Reza Davarani Mirzaei

    if when click on back and close the app see “unfortunately all has stop working ”
    add bellow code to AndroidBuildingMusicPlayerActivity.java

    @Override
    public void onBackPressed() {
    mHandler.removeCallbacks(mUpdateTimeTask);
    super.onBackPressed();
    }

  • Pankaj Singh Rawat

    how to run .m4a file in audio player or convert to .m4a to mp3?

  • shan

    i have tried every single thing mentioned in the comments below but still its not working..

    can anyone please help me ????

    “unfortunately all has stop working ” pops out each time i open the app

  • Zaier

    Hi everybody,
    I am here just to mention that Ravi don’t know the difference between between Runnable and thread Runnable is NOT a thread and handler.post(runnable) is for running the runnable in the thread where the handler was created/ instantiated. So all this application is running in the UI thead.
    If I was him I would learn about multi-threading & then correct this tutorial.

  • Zaier

    Ravi my friend try this:
    in onCreate methode , just to be sure that you are in the UI thread and then see witch thread is created and called

    Runnable runnable=new Runnable() {
    @Override
    public void run() {
    Log.d(“ThreadName”,”currentThread() here “+ Thread.currentThread().getName());

    }
    };
    runnable.run();

    new Thread(new Runnable() {
    @Override
    public void run() {
    Log.d(“ThreadName”,”currentThread() here “+ Thread.currentThread().getName());

    }
    }).start();

  • surya Mouly

    can anyone help me in creating video player in android…. plz refer

  • Bréndou Serge Eric Kossonon

    HI!! can somebody send me the .psd file please ???

  • Gagan Agarwal

    App crashes when i click on play/pause/back/next rest everything is working fine

    FATAL EXCEPTION: main

    Process: com.example.gagan.musicplayer, PID: 19778

    java.lang.NullPointerException

    at com.example.gagan.musicplayer.MainActivity.playSong(MainActivity.java:286)

    at com.example.gagan.musicplayer.MainActivity.onCompletion(MainActivity.java:389)

    at android.media.MediaPlayer$EventHandler.handleMessage(MediaPlayer.java:2267)

    at android.os.Handler.dispatchMessage(Handler.java:102)

    at android.os.Looper.loop(Looper.java:136)

    at android.app.ActivityThread.main(ActivityThread.java:5086)

    at java.lang.reflect.Method.invokeNative(Native Method)

    at java.lang.reflect.Method.invoke(Method.java:515)

    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)

    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)

    at dalvik.system.NativeStart.main(Native Method)

  • sijo jose

    Hai Ravi,
    can i cantrol volume with gasture detection with seekbar like mxplayer?

  • thezainic

    how to integrate audio with lyric ???

  • Dharmendra

    After running the application Unfortunately Stoped how to solve this ??

  • Selva Kumar

    Hi Ravi,

    This is my first app and have to finish it asap, I tried opening in Android Visual Studio, I’m getting plenty of errors, could you please give me ,working code in Android studio,please.

    Based on your code and reply only, I have to sit and develop the rest of the code. Kindly help.

    email: Kumar.selva.c@gmail.com
    Anticipating your reply.

  • Selva Kumar

    Error! Error! Error!, I have wasted 4days of work jus by solving errors:-(

  • Selva Kumar

    Hi Ravi,
    I see most of comments given are about facing errors, I kindly request you to upload new working code,please. It would help many.

    Thanks.

    • Yeah, I have to but updating some other articles. I’ll update it whenever I get time.

  • Sunil Reddy

    hi

    did u get solution for this errors

  • Victor Cristian Rădulescu

    anyone knew how to start multple mp3 files from assets folder at the same time. Tryed a lot .

  • deepak

    this help me alot

  • Akshay kumar

    Hi Ravi, i have downloaded your source code and tried to run but it is not working, suggest me something

  • tohin

    Thanks Ravi bro, Everything thing is done perfectly

    • You are welcome 🙂

      • tohin

        Hi Ravi can u tell us how can we play music in background by Service

      • Muhammad Mubeen

        Ya I Got Error in GetPlayList();

        public ArrayList<hashmap> getPlayList(){
        File home = new File(MEDIA_PATH);

        if (home.listFiles(new FileExtensionFilter()).length > 0) {
        for (File file : home.listFiles(new FileExtensionFilter())) {
        HashMap song = new HashMap();
        song.put(“songTitle”, file.getName().substring(0, (file.getName().length() – 4)));
        song.put(“songPath”, file.getPath());

        // Adding each song to SongList
        songsList.add(song);
        }
        }w
        // return songs list array
        return songsList;
        }

        how to fix this please

  • cutitas cutit

    add this to the main activity so it for background or lock screen playng 🙂

  • Pranshu Sinha

    hello everyone..
    i have been trying to make this project but i am facing the same error as everyone i.e ava.lang.RuntimeException: Unable to start activity … i added the permissions in the manifest file and also changed the file path…. it is not running on emulator as well as the mobile phone.. pls help me… contact me on pranssin@gmail.com

  • nimahkh

    thank you for your nice code , i have a problem , i want to get all of musics from assets folder ( app assets folder ), how can i do this? it is very important for me , thank you

  • Jack

    Amazing tutorial, Ravi! I have made my own audio widget! Could you check it:
    https://github.com/Cleveroad/MusicBobber.

    • Looks awesome. Good work 🙂

      • nimahkh

        Ravi can you please guide me? i want to have my offline playlist and publish it for my users , i want users just listen to playlist that i make inside of application . how can i change /sdcard/ address to my resource from application ? thank you very much .

    • virinchi reddy

      Hey Jack I just went through your git hub account and want to develop a audio widget just like yours . Can i use your ‘s as a tutorial to develop my own android widget thank you . If it is okay then please mail me at yekkantivirinchireddy@gmail.com .

  • vinod

    When app opens unfortunaltely app stopped. whats the solutions!!!!!!!!!!plz any one help me….

  • Jerome

    Thank you for your wonderful work, I have a question :
    Is this code open-source?
    Can I reuse it even in a commercial app ?

    Thanks again

  • Pratik Saluja

    Awesome, Thank you

  • Osama Abu Nuwar

    How to download code???

  • Prayag Ramanuj

    error occur. while start activity.

    • David

      If you are using Android 6.0 you need to check and ask for storage permission.
      Did you made that ?

  • Vinoth Vino

    Thank you for the wonderful tutorial 🙂

  • Touchstone toucstone

    Everything is working like charm except when i hit back button of device , application is crashing with this exception
    Process: com.androidhive.musicplayer, PID: 29938
    java.lang.IllegalStateException

    I have also added permissions like Read and Write External Storage . Please help

    • Kedrian Fiwi Linkz James

      if your are clicking the back button and exiting update your ondestroy method to

      super.onDestroy();
      mHandler.removeCallbacks(mUpdateTimeTask);
      if(mp!=null)
      {

      if(mp.isPlaying()) mp.stop();
      mp.reset();
      mp.release();

      }

  • PRAFUL ANAND

    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.hp.insanemediaplayer/com.example.hp.insanemediaplayer.MusicPlayer}: java.lang.NullPointerException: Attempt to get length of null array
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Caused by: java.lang.NullPointerException: Attempt to get length of null array
    at com.example.hp.insanemediaplayer.SongsManager.getPlayList(SongsManager.java:28)
    at com.example.hp.insanemediaplayer.MusicPlayer.onCreate(MusicPlayer.java:79)
    at android.app.Activity.performCreate(Activity.java:6237)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native
    help me out sir fed up of getting this error Please help me 5 days since i have been stuck at this

    • Vincent Tirgei

      Did you solve this?.. I’m getting the same error

      • PRAFUL ANAND

        Not able to solve it

        • SmiK

          please check your SDCARD path..
          System.out.println(Environment.getExternalStorageDirectory().getAbsolutePath());
          and also make sure that, audio files exists in that location..

          In SongsManager class change :
          final String MEDIA_PATH = new String(“/sdcard/”);
          to
          your sdcard path.. im my case it is:
          final String MEDIA_PATH = new String(“/storage/emulated/0/”);

          Finally dont forget to add permisson:

          This worked for me.. 🙂

    • shylock Arinaitwe

      replace File(MEDIA_PATH)” by Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)” ;
      and add this permission to manifest file

      • An Nguyen

        11-05 18:31:15.494 2359-2359/com.androidhive.musicplayer E/AndroidRuntime: FATAL EXCEPTION: main
        Process: com.androidhive.musicplayer, PID: 2359
        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.musicplayer/com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity}: java.lang.NullPointerException: Attempt to get length of null array
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
        Caused by: java.lang.NullPointerException: Attempt to get length of null array
        at com.androidhive.musicplayer.SongsManager.getPlayList(SongsManager.java:25)
        at com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity.onCreate(AndroidBuildingMusicPlayerActivity.java:77)
        at android.app.Activity.performCreate(Activity.java:6237)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
        Please ! help me

  • Muhammad Abubakar

    I have a question how to convert psd Icons and Images to xml ???

  • Ajish Nair

    Hi It is not working properly. It is showing unfortunately app has been stopped.
    what is the issue

  • Hi, can I have a simple play, pause and stop button with seekhbar mediaplayer which can play from URL or better from string, is there any tutorial ?
    I have done some but i am unable to play from a URL or a String.
    I want to implement this audio player in your MultiLevel ListView, I already implemented VideoView which is working greate, and I need Audio player as well.

    • Kedrian Fiwi Linkz James

      1. Update your manifest to add internet permission

      2. implement on MediaPlayer.OnErrorListener and MediaPlayer.OnPreparedListener
      3. register the listeners
      4. update your the playSong(int songIndex) method to :
      // Play song
      try
      {
      // mp.reset();
      //if(mp.isPlaying()) mp.stop();

      Uri myUri = Uri.parse(songsList.get(songIndex).getMusicLink());

      if (mp == null)
      {
      this.mp = new MediaPlayer();
      mp.setOnCompletionListener(this); // Important
      mp.setOnPreparedListener(this);
      mp.setOnErrorListener(this);
      }
      else
      {
      if(mp.isPlaying())mp.stop();
      mp.reset();
      mHandler.removeCallbacks(mUpdateTimeTask);
      }

      mp.setDataSource(this, myUri); // Go to Initialized state
      mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
      buffering=true;
      updateLabelStatus(“Loading please wait…”);
      Log.d(TAG, “LoadClip Done”);
      mp.prepareAsync();

      } catch (IllegalArgumentException e) {
      e.printStackTrace();
      Log.d(TAG, e.toString());
      } catch (IllegalStateException e) {
      e.printStackTrace();
      Log.d(TAG, e.toString());
      } catch (IOException e) {
      e.printStackTrace();
      Log.d(TAG, e.toString());
      }
      }

      implement on prepare like this:

      Log.d(TAG, “Stream is prepared”);

      try
      {

      if(!mp.isPlaying()) mp.start();

      songProgressBar.setProgress(0);
      songProgressBar.setMax(100);
      // Updating progress bar
      updateProgressBar();
      // set Progress bar values

      buffering = false;
      // Displaying Song title
      songTitleStatus = songsList.get(currentSongIndex).getTitle();
      updateLabelStatus(songTitleStatus + ” – Playing”);

      // Changing Button Image to pause image
      btnPlay.setImageResource(R.drawable.ic_pause_arrw);

      }
      catch(Exception e)
      {
      doTost(“Error streaming media”);
      updateLabelStatus(songTitleStatus + ” – Stopped”);
      }

      finally implement on error listener

      @Override
      public boolean onError(MediaPlayer mp, int what, int extra)
      {
      StringBuilder sb = new StringBuilder();
      sb.append(“Media Player Error: “);
      switch (what) {
      case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
      sb.append(“Not Valid for Progressive Playback”);
      break;
      case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
      sb.append(“Server Died”);
      break;
      case MediaPlayer.MEDIA_ERROR_UNKNOWN:
      sb.append(“Station Server Down”);
      break;
      default:
      sb.append(” Non standard (“);
      sb.append(what);
      sb.append(“)”);
      }
      sb.append(” (” + what + “) “);
      sb.append(extra);
      Log.e(TAG, sb.toString());
      String ms = “Error: “+ songTitleStatus +” stream unavailable”;//sb.toString();
      doTost(sb.toString());
      updateLabelStatus(songTitleStatus + ” – Stopped”);
      buffering = false;
      return true;
      }

      • thanx, i will try this also, and i actually successfully done all that, but no seekhbar, i tried but seekhbar does not work.

  • Akshay Sharma

    Thanks ……
    Please tell me how to use listview of above songs in tabbed layout

  • Rishabh Kaushik

    There is a tiny error in onActivityResult() method in your main activity (AndroidBuildingSomethingActivity) dude. You tried to retrieve “songIndex” by getExtras() method from intent. It should be “songPath”.

  • 김다완

    hi, this page download source code link is wrong.
    plz, anyone help me!
    I want source Code. plz, sent to me E-mail.

    thanks!

    • It’s fixed now.

      • 김다완

        thank you!! Ravi~~~

  • Aqua

    hi, can u make a example about bassboost and equalizer android ? i have a problem with them

  • Nikss Paradva

    Hello I have problem at starting this activity

    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.musicplayer/com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity}: java.lang.NullPointerException: Attempt to get length of null array

    • Did you solve this?.. I’m getting the same error

      • Nikss Paradva

        Ya I Got Error in GetPlayList();

        public ArrayList<HashMap> getPlayList(){
        File home = new File(MEDIA_PATH);

        if (home.listFiles(new FileExtensionFilter()).length > 0) {
        for (File file : home.listFiles(new FileExtensionFilter())) {
        HashMap song = new HashMap();
        song.put(“songTitle”, file.getName().substring(0, (file.getName().length() – 4)));
        song.put(“songPath”, file.getPath());

        // Adding each song to SongList
        songsList.add(song);
        }
        }
        // return songs list array
        return songsList;
        }

        • thanks

          • Nikss Paradva

            welcome!!

          • Yuneeb Arshad

            if u remove getPlayList() it again give error

        • Ela

          How did you solve this problem?

          • Nikss Paradva

            Remove GetPlayList();

        • VIKASH KUMAR SWAMI

          If you remove getPlaylist() method …there is no way you will get the songs from the sdcard.
          It is not a solution, rather you are just removing the problem and ultimately the main purpose of the app.
          No Songs , Noting to Play.

          • Yuneeb Arshad

            has you solved this problem

  • Abhishek Lahoti

    can anyone send me the download link of this source code file fast

  • darpan

    how to add album art of my mp3 in this music app?

  • Vaibhav Chugh

    Caused by: java.lang.NullPointerException: Attempt to get length of null array
    at com.androidhive.musicplayer.SongsManager.getPlayList(SongsManager.java:27)

  • Vaibhav Chugh

    how can we read all mp3 songs from a whole mobile storage ….i cannot get all mp3 , i only getting from SD-Card…please help

  • umme sulaith

    in the UI of player im getting a rendering problem: ” invalid drawable tag Linear Layout”
    can anybody help asap pls …….

  • phu

    would you please email me this source code!!! haphu4247@gmail.com, Thanks a lot!!!

  • Rehan Gul

    can anyone help me fix this problem plz?

    Caused by: java.lang.NullPointerException: Attempt to get length of null array
    at com.example.rg.deadlab_1.SongsManager.getPlayList(SongsManager.java:26)
    at com.example.rg.deadlab_1.AndroidBuildingMusicPlayerActivity.onCreate(AndroidBuildingMusicPlayerActivity.java:76)

    • Aminju Muhammad

      Yeah i get same error, can anyone help us?

  • Need Help

    hi,can u help me design the chat app where we can listen to song as soon as we sign in/sign up.and we can watch video directly from group chat or share the video to your friend.thank you so much if u can help me.

  • sagar

    hi ravi, i want to download code but i’m unable to download . how can i download it help me please
    sagar22myagdi@gmail.com

    • Hi Sagar

      Please use Facebook / github to login.

      • sagar

        I tried but it is not working. please send link to github repository

      • ကို ဘုန္း

        Sir! How can I get all songs from both External and Internal storage.
        I downded source code and ran this.
        Now, I have a little problem.

      • ကို ဘုန္း

        java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

        That is my problem.And then

        final String MEDIA_PATH = new String(“/sdcard/”);

        instead of “/sdcard/” I made sure the path of songs
        But it still no Ok 🙁
        How can I fix it. Please reply me!!!
        Thz U

        • neha

          hello dear, i am getting same error , if you have resolved this issue , please help me …..

      • John Bang

        Hi Ravi, the same question, can you send link to github?

  • An Nguyen

    11-05 18:31:15.494 2359-2359/com.androidhive.musicplayer E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.androidhive.musicplayer, PID: 2359
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.musicplayer/com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity}: java.lang.NullPointerException: Attempt to get length of null array
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Caused by: java.lang.NullPointerException: Attempt to get length of null array
    at com.androidhive.musicplayer.SongsManager.getPlayList(SongsManager.java:25)
    at com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity.onCreate(AndroidBuildingMusicPlayerActivity.java:77)
    at android.app.Activity.performCreate(Activity.java:6237)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Please ! help me

    • Shyam Sunder

      Same here to me also.. RAVI I would appreciate if you can help us on this?

      • The code is very old and you need to debug it well. See on which line the null point exception is occurred?

        • Shyam Sunder

          ERROR:
          Caused by: java.lang.NullPointerException: Attempt to get length of null array
          at com.androidhive.musicplayer.SongsManager.getPlayList(SongsManager.java:25)
          at com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity.onCreate(AndroidBuildingMusicPlayerActivity.java:77)

          ========================================================
          In AndroidBuildingMusicPlayerActivity.java – 25th line
          & SongsManager.java – 77th line

        • John Bang

          SongManager.getPlaylist() in line 27, that stay block if

        • John Bang

          please can you help me? I have android 6.0.1, must i have a runtime permision in my code? if must then where i shoud to paste it?

        • Yuneeb Arshad

          Sir i need your help i want to get all the song which is present in sd card or phone memory if the sd card is not present it automatically get it from the phone

  • VIKASH KUMAR SWAMI

    Anyone please help me find these files : @layout/bg_player_header, @layout/bg_player_footer, @drawable/seek_handler.

  • Mukesh

    Excellent Article. kudos.

  • SAM

    10621-10621/com.androidhive.musicplayer E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.androidhive.musicplayer, PID: 10621
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.musicplayer/com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity}: java.lang.NullPointerException: Attempt to get length of null array
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5443)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
    Caused by: java.lang.NullPointerException: Attempt to get length of null array
    at com.androidhive.musicplayer.SongsManager.getPlayList(SongsManager.java:25)
    at com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity.onCreate(AndroidBuildingMusicPlayerActivity.java:77)
    at android.app.Activity.performCreate(Activity.java:6245)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5443)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

    • Sathish Balaram

      use media player permission

  • Shyam Sunder

    Ravi: Can you help me on this error? I’ve tested in mobile MotoG2

  • Sara

    Thank you for this tutorial! It is very thorough and extremely helpful for someone new to working with audio in Android.

    • You are welcome Sara.

      Happy Coding!

      • Ibnu Sameer

        Sir me too a new to it. I tested both on emulator and on real device. Both importing your project and also on my own project based on your tutorial. But application stops responding. Please help

  • Nguyễn Như Việt

    Thank You.. ^^

  • Nasrullah haq

    sir i cant install it in my real device

  • Amal p

    ———————————————————————————————————————————————
    Modify SongsManger like this and you have to pass context of appropriate activity during object creation of songsmanger in that activity

    I have corrected the code for getplaylist() function and dont forget to add runtime permission in manifest and also
    check the permission using a dialog box
    ——————————————————————————————————————————————————

    eg:

    SongsManager plm = new SongsManager(PlayListActivity.this);

    // get all songs from sdcard

    this.songsList = plm.getPlayList();

    ———————————————————————————————————————————————-

    public class SongsManager {

    private ArrayList<HashMap> songsList = new ArrayList<HashMap>();

    Cursor cursor;

    Context context;

    // Constructor

    public SongsManager(Context context){

    this.context = context;

    }

    /**

    * Function to read all mp3 files from sdcard

    * and store the details in ArrayList

    * */

    public ArrayList<HashMap> getPlayList(){

    String selection = MediaStore.Audio.Media.IS_MUSIC + ” != 0″;

    String[] projection = {

    MediaStore.Audio.Media._ID,

    MediaStore.Audio.Media.ARTIST,

    MediaStore.Audio.Media.TITLE,

    MediaStore.Audio.Media.DATA,

    MediaStore.Audio.Media.DISPLAY_NAME,

    MediaStore.Audio.Media.DURATION

    };

    ContentResolver contentResolver = context.getContentResolver();

    cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,projection, selection,null,null);

    while(cursor.moveToNext()) {

    HashMap song = new HashMap();

    song.put(“songID”,cursor.getString(0));

    song.put(“songTitle”,cursor.getString(2));

    song.put(“songPath”,cursor.getString(3));

    // Adding each song to SongList

    songsList.add(song);

    }

    // return songs list array

    return songsList;

    }

    }

    • Yuneeb Arshad

      Sir can i get the source code of this

      • Amal p
        • Yuneeb Arshad

          can u help me to get the thumbail of the audio

        • Yuneeb Arshad

          thanks Sir..
          but i made it but i want to get thumbnail of the audio songs and after a lot of search i stuck on it can you help me

        • Yuneeb Arshad

          Sir can u kindly help me on getting thumbnail on this source code i can get thumbnail but not on the exact position like first song thumbnail display on 3rd or 4th song

    • Yuneeb Arshad

      java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.androidpc.musicplayer/com.example.androidpc.musicplayer.MainActivity}: java.lang.NullPointerException: Attempt to get length of null array…..

      in SongsManager class
      need help

    • John Bang

      thank you Amal)))

  • Amal p

    Also extend each of your activity with appcombatActivity it contains the content resolver

  • Yuneeb Arshad

    Sir this download link not working properly

    • CMD Dzeko

      i didnt see any download links here..?

      • DOWNLOAD CODE button is there on top.

        • Yacine

          I’m using Android Studio, i try to build the Apk but I don’t arrived, please help me

  • ADevD

    Thanks Ravi…
    These were very useful for my Project work.
    Rest I faced some problems, worked few days onto them and googling I found there’s better Solution to the problem :: Java*Null*Exception
    I recommend using the following code in Songsmanager class to Create Playlist & Load Music Files.
    =============================================================================
    I found this code at
    http://stackoverflow.com/questions/12005566/how-to-play-mp3-files-from-internal-and-external-sd-card-in-android/
    =============================================================================
    package com.androidhive.musicplayer;
    import android.os.Environment;
    import java.io.File;
    import java.io.FilenameFilter;
    import java.util.ArrayList;
    import java.util.HashMap;
    public class SongsManager {

    final String MEDIA_PATH = Environment.getExternalStorageDirectory().getPath() + “/”;
    private ArrayList<HashMap> songsList = new ArrayList<HashMap>();
    private String mp3Pattern = “.mp3”;
    // Constructor
    public SongsManager(){
    }
    /**
    * Function to read all mp3 files from sdcard
    * and store the details in ArrayList
    * */
    public ArrayList<HashMap> getPlayList(){
    System.out.println(MEDIA_PATH);
    if (MEDIA_PATH != null) {
    File home = new File(MEDIA_PATH);
    File[] listFiles = home.listFiles();
    if (listFiles != null && listFiles.length > 0) {
    for (File file : listFiles) {
    System.out.println(file.getAbsolutePath());
    if (file.isDirectory()) {
    scanDirectory(file);
    } else {
    addSongToList(file);
    }
    }
    }
    }
    // return songs list array
    return songsList;
    }
    private void scanDirectory(File directory) {
    if (directory != null) {
    File[] listFiles = directory.listFiles();
    if (listFiles != null && listFiles.length > 0) {
    for (File file : listFiles) {
    if (file.isDirectory()) {
    scanDirectory(file);
    } else {
    addSongToList(file);
    }
    }
    }
    }
    }
    private void addSongToList(File song) {
    if (song.getName().endsWith(mp3Pattern)) {
    HashMap songMap = new HashMap();
    songMap.put(“songTitle”,
    song.getName().substring(0, (song.getName().length() – 4)));
    songMap.put(“songPath”, song.getPath());
    // Adding each song to SongList
    songsList.add(songMap);
    }
    }
    /**
    * Class to filter files which are having .mp3 extension
    * */
    class FileExtensionFilter implements FilenameFilter {
    public boolean accept(File dir, String name) {
    return (name.endsWith(“.mp3”) || name.endsWith(“.MP3”));
    }
    }
    }

  • Yuneeb Arshad

    java.lang.NullPointerException: Attempt to get length of null array

    //at this line
    if (home.listFiles(new FileExtensionFilter()).length > 0) {
    for (File file : home.listFiles(new FileExtensionFilter())) {
    HashMap song = new HashMap();
    song.put(“songTitle”, file.getName().substring(0, (file.getName().length() – 4)));
    song.put(“songPath”, file.getPath());

    // Adding each song to SongList
    songsList.add(song);
    }
    }
    // return songs list array
    return songsList;
    }

    • Anil Atri

      kindly check your path in sd card where mp3 file exist. then set it in this :- final String MEDIA_PATH = new String(“/storage/sdcard0/Music”);

  • Владимир Ковалёв

    Guys, I decided NillPointerExeption problem!
    First of all, add to the manifest this lines:

    Secondly, in the method OnCreate() paste the following code which requests permission to access files from the user (this thing has become necessary for Android 6 and above)
    Then, correct the path to the sd card in the class SongManager. (In my case, it looks like this:
    final String MEDIA_PATH = new String ( “/storage/830D-15FF/Music”); )
    Finally, in the same class completely delete the contents of the method:
    publics SongsManager()
    and insert the following code instead:

    public ArrayList<HashMap> getPlayList(){
    System.out.println(MEDIA_PATH);
    if (MEDIA_PATH != null) {
    File home = new File(MEDIA_PATH);
    File[] listFiles = home.listFiles();
    System.out.println(home.listFiles());
    if (listFiles != null) {
    for (File file : listFiles) {
    System.out.println(file.getAbsolutePath());
    if (file.isDirectory()) {
    scanDirectory(file);
    } else {
    addSongToList(file);
    }
    }
    }
    }
    // return songs list array
    return songsList;
    }

    private void scanDirectory(File directory) {
    if (directory != null) {
    File[] listFiles = directory.listFiles();
    if (listFiles != null && listFiles.length > 0) {
    for (File file : listFiles) {
    if (file.isDirectory()) {
    scanDirectory(file);
    } else {
    addSongToList(file);
    }
    }
    }
    }
    }

    private void addSongToList(File song) {
    if (song.getName().endsWith(mp3Pattern)) {
    HashMap songMap = new HashMap();
    songMap.put(“songTitle”,
    song.getName().substring(0, (song.getName().length() – 4)));
    songMap.put(“songPath”, song.getPath());
    // Adding each song to SongList
    songsList.add(songMap);
    }
    }

    /**
    * Class to filter files which are having .mp3 extension
    * */
    class FileExtensionFilter implements FilenameFilter {
    public boolean accept(File dir, String name) {
    return (name.endsWith(“.mp3”) || name.endsWith(“.MP3″));
    }
    }
    }

    I hope, this will help you 🙂

    UPD.
    I do not know why, but when the code insert extra characters appear in the type of strings:
    public ArrayList <HashMap > getPlayList ()
    Correct Strings in uppercase and delete the piece:
     =””

  • Yuneeb Arshad

    I am trying to add services and notification can any one help me

  • Leo Neo

    Awesome!!!! Thanks!! with this I can definitely build my own music player 🙂 🙂 You rock

    • Murtuza Ghadyali

      did it work for u
      shows 2 error in mine

  • rocking clrd po

    its a really great tutorial it help me to develop my music player app.

    Please check my music player app here thanks – https://play.google.com/store/apps/details?id=zerosound.music

  • Divya Gupta

    sir how to run this application on eclipse ??

  • Divya Gupta

    please tell me how to resolve these errors…

    [2017-03-11 18:27:46 – AndroidBuildingMusicPlayer] Automatic Target Mode: launching new emulator with compatible AVD ‘3.7_WVGA_(Nexus_One)_API_22’
    [2017-03-11 18:27:46 – AndroidBuildingMusicPlayer] Launching a new emulator with Virtual Device ‘3.7_WVGA_(Nexus_One)_API_22’
    [2017-03-11 18:27:47 – Emulator] emulator: ERROR: virtual device name contains invalid characters

    • Aryan Sharma

      Rather than using a VIRTUAL DEVICE , prefer to use it in your phone ,by enabling the DEVELOPERS option in your phone and connecting it to the PC/LAPTOP , it will run and load faster than your AVD.

  • Shami

    Hi Awesome code but it got few bugs like u r using Runnable which keep on running and we are not shutting it down on activity stop or activity pause which could cause crash since our media player object is null and Runnable is still working…..

  • ABILASH SOMAN

    how to avoid stoping music on clicking back button(i need continuously playing song if we press back button)

  • ABILASH SOMAN

    how to add services for playing song in background????

  • Soft key

    How to add Music Equalizer animation ?? Please help

  • Panuwat Kumsaikaew

    How to delete mp3 file from listview ? please advice.

    • Yacine

      How did you arrived to build the Apk, please Tell me

      • Benz Panuwat

        I just follow up this tutorial.

  • UBAID ABBASI

    Not Working I got Error
    Caused by: java.lang.NullPointerException at SongsManager.getPlayList(SongsManager.java
    any one guide?

  • Tavish Barua

    Need Help! How can i separate Service and create a dedicated service file so that i can bind that service with the activity later .

  • Tavish Barua

    Need Help! How can i separate Service and create a dedicated service file so that i can bind that service with the activity later .

  • kamal

    I want the list of songs in the main screen then user click on the song then the media player opens….what to do for that

  • Saubhik Singh

    How to fetch all the songs from everywhere.

    • Anil Atri

      get all mp3 file : Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
      to check use Log.e(TAG, “onCreate:list_cursor “+cursor.getCount() );

  • yash

    is the onclick on next button taking care of the fact that the user might have shuffle on…so it has to play a random song on next button click, maybe i am wrong but i did not find the code to care of this condition.

  • suriya pandian

    i downloaded your code and compiled it through my eclipse. but my apk is not working properly

  • Angga

    How to play mp3 in to apk raw folder?
    Tanks