Search code examples
androidmedia-player

MediaPlayer to play music across Activites


I'd like to play music across Activities and I'm using a simple class to implement it. This class ( BackgroundMusic ) starts the music with MediaPlayer when I call the startMusic() method and stops it when I call the stopMusic() method. When I use it only in one Activity it works perfectly. OnCreate calls startMusic() method and onPause calls stopMusic() method and the MediaPlayer behave on the right way. The problem starts when I'd like to move to another Activity. When I'd like to stop the music it throws me NullPointerExepction for the mediaplayer.stop() . So it looks like the app thinks that I want to stop a never started MediaPlayer. I tried to call the startMusic() method in every onCreate method but the music starts again and again and I'd like to play only one music which don't stop and starts again when I move to another Activity. Is it possible to do that with class or I have to use Service? I hope you can help me to that with class.

BackgroundMusic

public void startMusic() {
    mediaPlayer1 = MediaPlayer.create(context, R.raw.zenenegy);
    if(palya <= 5 || palya > 15){
        mediaPlayer1.start();
        mediaPlayer1.setVolume(0.2f, 0.2f);
        mediaPlayer1.setLooping(true);
        play = true;
    }
}

public void stopMusic(){
    if(play){
        mediaPlayer1.stop();
        mediaPlayer1.reset();
        mediaPlayer1.release();
        mediaPlayer1 = null;
        play = false;
    }
}

An Activity

  BackgroundMusic bm;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fomenu);

    bm = new BackgroundMusic(mentes,this);

    if(sounds){
        bm.startMusic();
    }
}

@Override
protected void onPause() {
    if(sounds){
        bm.stopMusic();
    }
    super.onPause();
}

Solution

  • If I set the mediaplayer to static in the BackgroundMusic it works perfectly.