How to close a running audio

Asked

Viewed 146 times

1

I’m creating an application that performs a sound or a song, but I can’t make the sound stop. This way I am forced to stop the application manually so that the sound stops. How can I stop the music by pressing 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();}

2 answers

1


The MediaPlayer has methods pause() and stop() which serve to pause and stop the audio execution respectively.

The problem here is that you are creating the MediaPlayer as a local variable to your method. With this, you are letting it "leak". Instead of declaring it in this method, declare it as a member of the Activity and just initialize it within the method. Done this, let’s say your pause button is called pausarButton and your Mediaplayer keeps calling mp, then 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 are no longer using (which may not be just when the audio runs out) and make sure that the audio does not restart while rotating the screen.

  • Hello Pablo, first thank you very much, your help was very important.

  • Following his guidelines I managed to add a "pause" button and the "stop" button, only the "pause" worked correctly, the problem was that when the sound was stopped using the "stop" button it was not possible to start the sound again, but there is no problem, with the "pause" button working is what matters.

0

With my changes my code was 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();
      }
});}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.