How to stop the mediaplayer playing from other methods

梦想与她 提交于 2020-01-14 06:22:07

问题


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.


回答1:


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();



回答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.



来源:https://stackoverflow.com/questions/16418589/how-to-stop-the-mediaplayer-playing-from-other-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!