Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting an array of songs using MediaPlayer

I have 5 songs which i need to play one after the other, and it must loop from the first song after finishing the 5th song. How do I use the MediaPlayer to achieve this?

like image 743
Nikhil Avatar asked Dec 17 '22 09:12

Nikhil


1 Answers

public class MediaPlayerExample extends Activity implements MediaPlayer.OnCompletionListener {
 int [] songs;
MediaPlayer mediaPlayer;
int current_index = 0; 
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

songs= new int[] {R.raw.song1,R.raw.song2,R.raw.song3,R.raw.song4};

mediaPlayer = MediaPlayer.create(this, songs[0]);

mediaPlayer.setOnCompletionListener(this);

mediaPlayer.start();

}
@Override
    public void onCompletion(MediaPlayer mp) {
        play();

    }

 private void play()
    {
        current_index = (current_index +1)% 4;
        AssetFileDescriptor afd = this.getResources().openRawResourceFd(songs[current_index]);

        try
        {   
            mediaPlayer.reset();
            mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
            mediaPlayer.prepare();
            mediaPlayer.start();
            afd.close();
        }
        catch (IllegalArgumentException e)
        {
            Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
        }
        catch (IllegalStateException e)
        {
            Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
        }
        catch (IOException e)
        {
            Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
        }
    }
}
like image 173
confucius Avatar answered Jan 18 '23 04:01

confucius