How to get Android MediaPlayer() to stop when app is closed? - android

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();
}

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...

Also think about onResume(), to continue your looping song when the user comes back to your app.

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. :)

Related

Why mediaPlayer plays 15 minutes and then stop?

when I lock my Android Screen,my app is still playing music(it means the mediaPlayer is working),but after 15 minutes,the music will be stoped,dou you know why?
(I did not use Service or BindService at all,just Use MediaPlayer Class)
Yes it happens, why?
because I think you are using MediaPlayer in Activity, and android release some untouched resources after some time to give space to other processes.
you have to use foreground Service to prevent this problem.
Here is example of MediaPlayer inside Service.
https://stackoverflow.com/a/8209975/6676466
Release the player memory by using onDestroy() method
#Override
public void onDestroy() {
if (mp!= null) mp.release();
}

How to play background sound through out application?

How can I play Background Sound throughout my application, even if activities keeps on changing.
I have found code for playing sound in background for one activity as:
public class BackgroundSound extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
MediaPlayer player = MediaPlayer.create(YourActivity.this, R.raw.test_cbr);
player.setLooping(true); // Set looping
player.setVolume(100,100);
player.start();
return null;
}
}
I am not getting anyway to play sound in application content not activity context.
So I think there must be some way to achieve this using singleton class or service?
Play Background Sound in android applications
How to play audio in android
I have followed above both links but it doesn't seems to help me though, its playing sound but not with my instruction from second time, first it works where ever I want to start.
Any Help would be highly appreciated!!!

How to stop sound after Screen Lock

Hi I need to stop sound from mediaplayer on screen Lock As I am using
if(mp!= null && mp.isPlaying()){
mp.stop();
}
in onPause() . But there is no result. So, How can I stop my media player sound after screen is locked.
To say exactly, I have 16 mp3 files, which will come in random.if a sound is playing and the screen is locked, present sound is Stopped and next one sound is playing.After screen is unlocked, it will works as proper & when the screen is locked , Again same is repeating on my Android 2.3.6 version mobile. How to overcome this.
Thank you.
I have already faced with similar issue, the following code solved my problem:
#Override
public void onPause()
{
super.onPause();
PowerManager mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (!mPowerManager.isScreenOn())
if (mp!= null && mp.isPlaying())
mp.stop();
}
You would need to handle it via Screen On & Off intents.
See the link below for details:
http://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/
I think You need to set up your code to stop sound in receiver of
Screen off
here is more detail about how to deal with screen lock receiver . http://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/

How to check something at regular intervals?

Beginner here, I have a simple question.
In Android what would be the best what to check for something at regular intervals?
Please bear with me, I'll try to explain the best I can --
For example my audio app is very simple, a main activity and a service. The main activity has a UI with two buttons, start and stop audio. I press start and the audio service starts. Likewise when I click Stop the service stops and the audio ends. If isLooping() is hard-coded to true there is no issue because the audio never ends unless I hit stop button, which stops the audio service and also resets the button states.
This is an issue now because I set isLooping() to false so the audio doesn't loop. So the audio will stop playing but the service is still running.
I want to be able to detect when the audio stops so I can set the states of the UI buttons. So I need something that is always checking whether audio is playing (i.e. check player.isPlaying() so I can end the service and set the enable/disable state of the buttons.
I figured out binding to the service so I can access the MediaPlayer controls via my main activity so I know the code to check if it's playing, but WHERE do I put this code so it's checked all the time?
Am I making sense? I know this is probably very simple. Thanks for any help.
You can repeat it with the TimerTask and Timer. Code below:
public final void RepeatSoundFunction(){
t = new Timer();
tt = new TimerTask() {
#Override
public void run() {
mp.seekTo(0); //Reset sound to beginning position
mp.start(); //Start the sound
t.purge(); //Purge the sound
}
};
t.schedule(tt, 10*1000); //Schedule to run tt (TimerTask) again after 10 seconds
}
then you set a MediaPlayer onCompletionListener and in there you put this.
Inside the run-code you can check for other things than
music, I just show an example with the audio.

How to play audio in splash screen in android

How to play an audio during splash screen.
Guidance needed.
My way to do this (no external sound needed, since I put my soundfile in my resources-folder):
In onCreate:
mp = MediaPlayer.create(getBaseContext(), R.raw.sound); /*Gets your
soundfile from res/raw/sound.ogg */
mp.start(); //Starts your sound
//Continue with your run/thread-code here
Remember to have the sound in .ogg-format; it's fully supported in Android.
An important thing below about handling the sound when the Splash Screen activity is stopped:
There are two general ways to manage the Splash Screen (and the sound inside it) when it's stopped:
Destroy the whole activity:
protected void onStop() {
super.onStop();
ur.removeCallbacks(myRunnable); /*If the application is stopped;
remove the callback, so the next time the
application starts it shows the Splash Screen again, and also, so the
thread-code,
don't continue after the application has stopped */
finish();
onDestroy();
}
Or you can just stop the sound in onStop:
protected void onStop() {
super.onStop();
if(mp.isPlaying()){ //Must check if it's playing, otherwise it may be a NPE
mp.pause(); //Pauses the sound
ur.removeCallbacks(myRunnable);
}
}
If you choose the second alternative you also have to start your Callback and MediaPlayer in the onStart-method.
I prefer the first alternative.
You can play audio files using the MediaPlayer class.
Example
MediaPlayer player = new MediaPlayer();
player.setDataSource("/sdcard/audiotrack.mp3");
player.prepare();
player.start();

Categories

Resources