Azhar Red
Azhar Red

Reputation: 3

how to stop audio on android application

I want to stop audio when pressing return or back button

public class buttonFour extends Activity{ 

    MediaPlayer mp;

    @Override 
    public void onCreate (Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.button4);

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

I have tried the following:

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

but the music keep playing

Upvotes: 0

Views: 2501

Answers (3)

Nadeem Iqbal
Nadeem Iqbal

Reputation: 1

try to make MediaPlayer object global... this works for me with the Global MediaPlayer object.

and then

mp.stop();

Upvotes: 0

Ahmad Y. Saleh
Ahmad Y. Saleh

Reputation: 3349

You are initializing another local MediaPlayer object mp inside onCreate(), thats why the instance variable never gets initialized, and never paused.

Just use the instance variable by replacing the line:

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

with

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

Upvotes: 1

A--C
A--C

Reputation: 36449

Make your MediaPlayer reference a global one.

Then override onBackPressed()

public class buttonFour extends Activity {
MediaPlayer mp;
    @Override
    public void onCreate (Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.button4);

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

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

Edit, although the above should work, if it isn't you can try something like this:

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

However this code will stop playback once the Activity goes off screen or upon a rotation change.

Upvotes: 2

Related Questions