Closing a running audio

1

I'm creating an application that plays a sound or a song, but I can not seem to stop it. This way I have to stop the application manually so the sound stops. How can I stop the music at the push of a button?

The code I'm using is this:

public void repro(View view){

        MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.som); mp.setOnCompletionListener(new OnCompletionListener() {

                @Override public void onCompletion(MediaPlayer mp) {

                    mp.release(); }

            }); mp.start();}
    
asked by anonymous 26.07.2016 / 03:06

2 answers

1

MediaPlayer has methods pause() and stop() which are used to pause and stop the execution of the audio respectively.

The problem here is that you are creating MediaPlayer as a local variable to your method. With that, you're letting him "leak". Instead of declaring it in this method, declare it as a member of Activity and just initialize it within the method. So, let's say your pause button is called pausarButton and your MediaPlayer keeps calling mp , so do something like this:

pausarButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        mp.pause();
    }
});

Of course this is just the beginning. There are other things to worry about, such as releasing MediaPlayer with release() when you no longer want to use it (which may not be just when the audio finishes) and take care that the audio does not restart when you rotate the screen. p>     

26.07.2016 / 03:26
0

With my changes, my code looks like this:

    Button play = (Button) findViewById(R.id.botão_play);
        Button pausar = (Button) findViewById (R.id.botão_pause);

    final   MediaPlayer mp = MediaPlayer.create(MainActivity.this,R.raw.som);
        play.setOnClickListener(new View.OnClickListener(){ 
        @Override
      public void onClick(View v){
            mp.start();}});

        pausar.setOnClickListener(new View.OnClickListener() {  
        @Override
     public void onClick(View v){
                mp.pause();
      }
});}
    
26.07.2016 / 13:31