Stop playing the sound when exiting the application

1

I'm creating an application, in JAVA , which plays songs by pressing a button. But when you press the button again, the song is repeated. And I'd like to stop it by touching the same button.

package dagustin.southamericamemes;

import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

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

    public void onClickTocar(View view){

        MediaPlayer mp = MediaPlayer.create(this , R.raw.morre);
        mp.start();

    }

}
    
asked by anonymous 20.03.2017 / 20:07

1 answer

3

So:

import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;


public class MainActivity extends AppCompatActivity {
    private MediaPlayer mp

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

    public void onClickTocar(View view) {
        if (mp != null) {
            mp.reset();
        } else {
            mp = MediaPlayer.create(this, R.raw.morre);
            mp.start();

        }
    }


    @Override
    public void onPause() {
        super.onPause();
        if (mp != null) {
            mp.stop();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mp != null) {
            mp.release();
        }

    }
}
    
20.03.2017 / 20:44