0

I am using this setOnClickListener() inside an one of the method in my Android App.Here I have used A mediaPlayer, which is declared locally. Like this I also have two more methods which all uses mediaplayer. Also I have declared a global Mediaplayer & used it in various places of my onCreate().

public void setOnClickListenerWithMedia(ImageView iv,final int drawable,final int sound) {
    iv.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            stopAllSoundsAndClearMemory();
        switchCases();
        iv_gone();
        fullscreenImage.setVisibility(View.VISIBLE);
        fullscreenImage.setImageResource(drawable);
        MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), sound);
        mediaPlayer.start();
        }
    });
}

My problem is if I click on any other method, I have to stop the MediaPlayer. For Globally declared MediaPlayer Object(mp.). I can directly use,

if(mp!=null&&mp.isPlaying()){
  mp.stop();
}

and I can stop it. But I also want to stop the sound from all the methods. How is it possible?

P.S: -> If I use mp in all the methods , it is not playing the sound & saying to create static mediaPlayer.

Thank you.

sai
  • 548
  • 10
  • 30
  • What methods are you talking about? What are they supposed to do? – Cornholio May 07 '13 at 12:09
  • Plz see the edited code,I will create two more methods like this and use them somewhere in my code. If I call this method , sounds from other methods should be stopped. That's it. – sai May 07 '13 at 12:15
  • In that case, you should just use a global MediaPlayer for everything. – Cornholio May 07 '13 at 12:24
  • Please see this one: https://stackoverflow.com/a/75423050/12272687 – Mori Feb 11 '23 at 20:34

2 Answers2

2

Every time when you are creating new player assign it to Global MediaPlayer instance.

i.e

declare mediaPlayer like this

MediaPlayer mp;

And then in your onClick or in other other methods use like this

And check whether MediaPlayer already exist or not

f(mp!=null&&mp.isPlaying()){
  mp.stop();
  mp.release();
}
mp=MediaPlayer.create(getApplicationContext(), sound);
mp.start();
Pragnani
  • 20,075
  • 6
  • 49
  • 74
2

try to design your mediaplayer as a singleton mode, and then your mediaplayer will be created only one instance object through the whole app.

3h3
  • 722
  • 5
  • 6