Search code examples
javaandroidandroid-mediaplayer

Media player play next song after completion of the first one


I want to make a program that will automatically play the next song after the one ends variables;

String path = "/mnt/sdcard/Music/";
String[] fileArray;
public int songNumber = 0;

MediaPlayer mPlayer = new MediaPlayer();
public boolean isPlaying = false;
public boolean isPaused = false;`

the void is;

 private void playMusic(String song){
    if(!isPlaying) {
        try {
            mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mPlayer) {
                    songNumber = songNumber + 1;
                    playMusic("/mnt/sdcard/Music/" + fileArray[songNumber]);
                }

            });

            mPlayer.reset();
            Toast.makeText(getApplicationContext(), song, Toast.LENGTH_SHORT).show();
            mPlayer.setDataSource(song);
            mPlayer.prepare();
            mPlayer.setOnCompletionListener((OnCompletionListener) this);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("Exception of type : " + e.toString());
            e.printStackTrace();
        }

        mPlayer.start();
        isPlaying = true;
    }else{
        stopMusic();
    }
}

However nothing is working, after the first song ends nothing happens


Solution

  • Changing the code on the void to this

    private void playMusic(String song){
        if(!isPlaying) {
            try {
                mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mPlayer) {
                        isPlaying = false;
                        mPlayer.reset();
                        songNumber = songNumber + 1;
                        playMusic("/mnt/sdcard/Music/" + fileArray[songNumber]);
                    }
    
                });
                Toast.makeText(getApplicationContext(), song, Toast.LENGTH_SHORT).show();
                mPlayer.setDataSource(song);
                mPlayer.prepare();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (Exception e) {
                System.out.println("Exception of type : " + e.toString());
                e.printStackTrace();
            }
    
            mPlayer.start();
            isPlaying = true;
        }else{
            stopMusic();
        }
    }
    

    Is gonna fix the problem