Reputation: 901
My android app creates a MediaPlayer() and plays a looping song. I need to have it stop playing when the user leaves the app. I also need to get at the volume buttons somehow, to let users adjust the songs volume... Any Ideas?
MediaPlayer mp;
public void setupMediaPlayer()
{
mp = MediaPlayer.create(context, R.raw.song);
mp.setLooping(true);
mp.start();
}
public void stopMediaPlayer()
{
mp.stop();
}
Upvotes: 3
Views: 6787
Reputation: 407
stopMediaPlayer didn't work for me as per eldarerathis' answer but this did:
@Override
protected void onPause() {
super.onPause();
releaseMediaPlayer();
}
Dunno why though...
Edited:
According to the course I'm doing though this is the correct way to do it.
Maybe one day I'll figure out the difference. :)
Upvotes: 1
Reputation: 3133
Also think about onResume(), to continue your looping song when the user comes back to your app.
Upvotes: 1
Reputation: 36213
Per the first half of your question: you should get what you want if you call stopMediaPlayer()
inside onPause()
and onDestroy()
. Example:
@Override
protected void onPause() {
super.onPause();
stopMediaPlayer();
}
Per the second half: Try taking a look at the AudioManager class (particularly AUDIO_FOCUS_GAIN), and see if that can handle what you're looking for.
Make sure the looping audio makes sense in the context of the app, though...if there's one thing I don't miss from the amateur websites of the mid-90's it's that awful MIDI background music that everyone seemed to put in them...
Upvotes: 2