Search code examples
javaandroidandroid-mediaplayer

why is my third song not playing and how can I make it play?


I am currently playing one song and after my first song ends the second song starts playing. When my second song ends the third song should start playing but it's not. How can I do this using the MediaPlayer.

This is my onCompletion code:

@Override
public void onCompletion(MediaPlayer mp) {
    didFinishFirst = true;
    if(didFinishFirst) {

        Uri songUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.two);

        mp = MediaPlayer.create(getApplicationContext(), songUri);
        mp.start();
        mState = STATE_INITIALIZED;
        didFinishSecond = true;
    } else if(didFinishSecond){
        Uri songUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.three);

        mp = MediaPlayer.create(getApplicationContext(), songUri);
        mp.start();
        mState = STATE_INITIALIZED;
        didFinishThird = true;
    }
    mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

        @Override
        public void onPrepared(MediaPlayer mp) {
            // No need
        }
    });
}

Solution

  • You need to link the completion listener again to the new media player instance return by MediaPLayer.create. only then the oncompletion will be triggered

    Override
    public void onCompletion(MediaPlayer mp) {
        didFinishFirst = true;
        if(didFinishFirst) {
    
            Uri songUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.two);
    
            mp = MediaPlayer.create(getApplicationContext(), songUri);
            mp.start();
            mState = STATE_INITIALIZED;
            didFinishSecond = true;
            mp.setOnCompletionListener(this);
            // ^^^^^^^^^^^^^^^^^^^^^^
        } else if(didFinishSecond){
            Uri songUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.three);
    
            mp = MediaPlayer.create(getApplicationContext(), songUri);
            mp.start();
            mState = STATE_INITIALIZED;
            didFinishThird = true;
            mp.setOnCompletionListener(this);
            // ^^^^^^^^^^^^^^^^^^^^^^
        }
        mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
    
            @Override
            public void onPrepared(MediaPlayer mp) {
                // No need
            }
        });
    }