Android: How to keep reference to Media Player? - android

I'm building an application which players sound using the Media Player class.
If I use the back button to go to the menu and then reopen the app the music is still playing but if I play another track, the app seems to create a new media player. I can't put a reference saved instance state because it isn't serializble.
What's the recommended technique for keeping the reference?
Regards.

I would recommend you place your MediaPlayer behind a Service. I've found that a really good example of how to do this, as well as bind to that service and play media, is the NPR Radio app which is open source. You can find the source here

Take a look at the lifecycle diagram of Activity, and make sure you're not creating multiple MediaPlayer objects without releasing the old ones. http://developer.android.com/reference/android/app/Activity.html
Are you using MediaPlayer.create()? That allocates a new MediaPlayer object, but doesn't do anything to the old one. Call release() before calling create() a second time.
playSound(){
mp.release();
mp = MediaPlayer.create();
mp.start();
}
If you're managing it manually try putting your calls in these places.
onCreate(){
mp=new MediaPlayer();
}
onDestroy(){
mp.release();
wl.release();
}
playSound(){
mp.reset();
mp.setDatasource();
mp.prepare();
mp.start();
}
stopSound(){
mp.reset();
}
To keep the sound playing
onCreate(){
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "com.pzizz");
}
playSound(){
wl.acquire();
}
onDestroy(){
wl.release();
}
stopSound(){
wl.release();
}
add this to your manifest for wakelock permissions:
<uses-permission android:name="android.permission.WAKE_LOCK" />

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

Audio will not play when awakened from sleep mode (android)

I'm writing an Android alarm app. I can get the activity to come up all right when the alarm is triggered (it wakes the phone up, turns off the keyguard and shows the alarm view), but I can't for the life of me get the alarm to sound if the device is in sleep mode when the alarm goes off. (It does sound perfectly when the device is awake and the keyguard is on.) I am using a wake lock. I've tried using the MediaPlayer and the SoundPool with no success. Is there some kind of permission that I'm missing? (I already have WAKE_LOCK, DISABLE_KEYGUARD, and RECEIVE_BOOT_COMPLETED permissions.)
When debugging using the SoundPool I perform the load which returns a valid sound ID integer (1), but the onLoadComplete listener (this is where the sound gets played) is never fired. It fires just fine when the device is awake.
Anyone out there have any ideas or have run into the same problem?
Found the solution! I had the call to play the audio in the onCreate() method of the class. I moved it to onResume() as this is when you know the device is fully awake and the activity is visible, on top and in focus.
I recently encountered the same problem. The way I solved this was reading your answer, but also checking the activity flow by logging what was happening. Basically onCreate, onStart, onResume, onPause, onStop, onStart, onResume was being fired in that order. This was an activity that was started as an alarm screen.
I kept the initialization code in the onStart method, making sure to use .prepare() instead of prepareAsync() since I'm using local sounds.
try {
Log.d(LOG_TAG, "Setting media player URI: " + alarmTone.toString());
//mMediaPlayer = MediaPlayer.create(this, );
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(getApplicationContext(), alarmTone);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mMediaPlayer.setLooping(true);
mMediaPlayer.setVolume(100, 100);
mMediaPlayer.prepare();
} catch (Exception ex) {
Log.d(LOG_TAG, "Exception from media player: " + ex.getMessage());
}
Then inside the onPause and onStop methods, I added:
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
}
Inside the onResume method I added the media playing code:
if (mMediaPlayer != null && !mMediaPlayer.isPlaying()) {
Log.d(LOG_TAG, "Playing alarm through Media Player");
mMediaPlayer.start();
}
Huzzah, it works!

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

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

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