Home > other >  MediaPlayer not playing after reopening the app
MediaPlayer not playing after reopening the app

Time:06-25

When i add mediaplayer.start in onResume i was expecting to start the audio when i reopen the the app but it dindt start it

public MediaPlayer mediaPlayer;
int length = 0;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
  mediaPlayer = MediaPlayer.create(this, R.raw.andhadhun);
        mediaPlayer.start();
}
 @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        mediaPlayer.pause();
        length = mediaPlayer.getCurrentPosition();

    }

    @Override
    protected void onResume() {
        super.onResume();
        mediaPlayer.setOnPreparedListener(MediaPlayer::start);

    }

CodePudding user response:

This will work, It pauses the MediaPlayer in onStop and resume in onResume

public class MainActivity extends AppCompatActivity {
    private MediaPlayer mediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mediaPlayer = MediaPlayer.create(this, R.raw.audio);
        mediaPlayer.start();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!mediaPlayer.isPlaying() && mediaPlayer != null) {
            mediaPlayer.start();
        }
    }
}

CodePudding user response:

ok try this code

private MediaPlayer mediaPlayer = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

        mediaPlayer = MediaPlayer.create(this,R.raw.test);
        mediaPlayer.start();

}

@Override
protected void onPause() {
    if(mediaPlayer!=null)
        mediaPlayer.pause();
    super.onPause();
}

@Override
protected void onResume() {
    super.onResume();
    if(mediaPlayer!=null) {
        mediaPlayer.start();
    }
}
  • Related