Play all songs from your raw directory in ANDROID continuously.

By | February 10, 2011

In ANDROID all resource has a unique resource ID which we get by passing the song name to the function below playSong().

The function getAllResourceIDs() will convert this String which is the name of the song to the unique resource ID which can then be used to play the song.

setOnCompletionListener() will be executed when the MediaPlayer completes playing a song with in which you can call this function again with next song parameter to play the next song.

public int songId = 0;
public void playSong(String to_play_song)
{
       songId = getAllResourceIDs(R.raw.class, to_play_song);
       mp = MediaPlayer.create(geetaact.this,songId);
       try
       {
               mp.prepare();
       }
       catch (IllegalStateException e) {
                  e.printStackTrace();
       } catch (Exception e) {
                 e.printStackTrace();
       }
       mp.start();

       //Called when the song completes.....
      mp.setOnCompletionListener(new OnCompletionListener()
      {
	      public void onCompletion(MediaPlayer mp)
	      {
	            //Get next song and play again continuosly.
	     }
	  );
}

//function which returns the unique resource ID.
public static int getAllResourceIDs(Class c, String song) throws IllegalArgumentException
{
           //System.out.println("inside HashMap"+ song);
       HashMap resmap = new HashMap();
       java.lang.reflect.Field[] fields = c.getFields();
       try
       {
               for(int i = 0; i < fields.length; i++)
               {
	               if(song != null)
	                     if(fields[i].getName().startsWith(song))
	                        resmap.put(fields[i].getName(), fields[i].getInt(null));
	                else
	                     resmap.put(fields[i].getName(), fields[i].getInt(null));
               }
       } catch (Exception e)
       {
                  throw new IllegalArgumentException();
       }
       Integer one = (Integer) resmap.get(song);
       int songid = one.intValue();
       return songid;
   }
}

Leave a Reply

Your email address will not be published.