David G
David G

Reputation: 325

Stop audio playing on backpress

I have an activity when i click on play button and it plays mp3 sound. When I click back the audio still plays in the background and can also run alongside other audio sounds which is annoying. I have tried to implement other methods used on here but to no avail.

Code:

public class InstructionsManualActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_instructions_manual);
    Button one = (Button) this.findViewById(R.id.instructionsManual_but);
    final MediaPlayer mp = MediaPlayer.create(this, R.raw.instructions_manual);
    one.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            mp.start();
        }
    });
}

}

I have tried this code but app crashes on back press

@Override
public void onBackPressed() {
    super.onBackPressed();
    if (mp.isPlaying()) {
        mp.stop(); // or mp.pause();
        mp.release();

Upvotes: 1

Views: 93

Answers (3)

Sachin Rajput
Sachin Rajput

Reputation: 4344

First of all declare the MediaPlayer object Globally

  MediaPlayer mp = null;  //Declaring globally so can access anywhere in activity.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_instructions_manual);
        Button one = (Button) this.findViewById(R.id.instructionsManual_but);
        mp = MediaPlayer.create(this, R.raw.instructions_manual);
        one.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                mp.start();
            }
        });
    }

When you are pressing back button in any activity onBackPressed() will be called , there you can stop you media player if playing.

 @Override
    public void onBackPressed() {
        super.onBackPressed();
       //Here you can stop your MediaPlayer
        if (mp != null && mp.isPlaying()) {
            mp.stop();
            mp.release();
        }
    }

Upvotes: 2

Arpit bandil
Arpit bandil

Reputation: 204

Your code is fine just check it before stop for null player

    super.onBackPressed();
if (mp!=null && mp.isPlaying()) {
    mp.stop(); // or mp.pause();
    mp.release();

Upvotes: 0

Kamlesh
Kamlesh

Reputation: 447

    Try this it's working for me   

     if (mp != null) {
                    mp.stop();
                    mp.release();
                    mp = null;
                    finish();
                }

Upvotes: 2

Related Questions