Play list of mp3 file with MediaPlayer in Android

Gualty picture Gualty · Jun 6, 2015 · Viewed 15.6k times · Source

I have a problem to reproduce more than one mp3 file using MediaPlayer in Android. I'm able to reproduce one single file but I did not find nothing useful to reproduce different files one after the other.

The code that now I use to reproduce one file is:

public MediaPlayer mediaPlayer = null;

public void playP(View view) {

    if (mediaPlayer == null) {
        mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.music);
    }
    mediaPlayer.start();

}

How can I modify it to reproduce more a list of file?

Thanks

Answer

Saptak Niyogi picture Saptak Niyogi · Jun 6, 2015

Create a list of the music that you want to include in playlist. Then keep track of the music that is playing and once finished start the next in the list.

Like this

import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;


public class MainActivity extends AppCompatActivity {

    Timer timer;
    MediaPlayer mp;
    ArrayList<Integer> playlist;
    int i=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        playlist = new ArrayList<>();
        playlist.add(R.raw.a1);
        playlist.add(R.raw.a2);
        mp = MediaPlayer.create(this,playlist.get(0));
        mp.start();
        timer = new Timer();
        if (playlist.size()>1) playNext();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void playNext() {
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                mp.reset();
                mp = MediaPlayer.create(MainActivity.this,playlist.get(++i));
                mp.start();
                if (playlist.size() > i+1) {
                    playNext();
                }
            }
        },mp.getDuration()+100);
    }

    @Override
    public void onDestroy() {
        if (mp.isPlaying())
            mp.stop();
        timer.cancel();
        super.onDestroy();
    }
}