I'd like to play music across Activities and I'm using a simple class to implement it. This class ( BackgroundMusic ) starts the music with MediaPlayer when I call the startMusic() method and stops it when I call the stopMusic() method. When I use it only in one Activity it works perfectly. OnCreate calls startMusic() method and onPause calls stopMusic() method and the MediaPlayer behave on the right way. The problem starts when I'd like to move to another Activity. When I'd like to stop the music it throws me NullPointerExepction for the mediaplayer.stop() . So it looks like the app thinks that I want to stop a never started MediaPlayer. I tried to call the startMusic() method in every onCreate method but the music starts again and again and I'd like to play only one music which don't stop and starts again when I move to another Activity. Is it possible to do that with class or I have to use Service? I hope you can help me to that with class.
BackgroundMusic
public void startMusic() {
mediaPlayer1 = MediaPlayer.create(context, R.raw.zenenegy);
if(palya <= 5 || palya > 15){
mediaPlayer1.start();
mediaPlayer1.setVolume(0.2f, 0.2f);
mediaPlayer1.setLooping(true);
play = true;
}
}
public void stopMusic(){
if(play){
mediaPlayer1.stop();
mediaPlayer1.reset();
mediaPlayer1.release();
mediaPlayer1 = null;
play = false;
}
}
An Activity
BackgroundMusic bm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fomenu);
bm = new BackgroundMusic(mentes,this);
if(sounds){
bm.startMusic();
}
}
#Override
protected void onPause() {
if(sounds){
bm.stopMusic();
}
super.onPause();
}
If I set the mediaplayer to static in the BackgroundMusic it works perfectly.
Related
I'm trying to pause and resume VideoView with MediaPlayer in activity onPause() and onResume() methods, but in onResume() method MediaPlayer throws java.lang.IllegalStateException. I didn't release MediaPlayer but I think MediaPlayer automatically released after activity paused.
How should I handle it?
private MediaPlayer mediaPlayer;
void prepareVideo() {
videoView = new VideoView(context.getApplicationContext());
String path = "android.resource://" + getPackageName() + "/" +
R.raw.my_video;
videoView.setVideoPath(path);
}
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer = mp;
mediaPlayer.start();
}
});
#Override
protected void onResume() {
super.onResume();
if (mediaPlayer != null) {
mediaPlayer.start();
}
}
#Override
protected void onPause() {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
super.onPause();
}
The exception:
Caused by: java.lang.IllegalStateException
at android.media.MediaPlayer._start(Native Method)
at android.media.MediaPlayer.start(MediaPlayer.java:1194)
at co.myapp.app.reborn.myappTestActivity.onResume(myappTestActivity.java:370)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1259)
at android.app.Activity.performResume(Activity.java:6347)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3110)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3152)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1400)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5530)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:734)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)
Take a look at the mediaplayer state diagram on android documentation
MediaPlayer state diagram
According to the diagram you have to call setDataSource() and prepare() before calling start().
Probably something wrong happened before. Your logcat should point you in the right direction.
My guess is that your mediaplayer is not in paused state but in stopped state. So you have to call prepare and then start, not just start.
Unfortunately in this way your playback will restart from scratch.
You can use seek command for resuming a position saved during the activity pausing.
We just need to implement MediaPlayer.OnSeekCompleteListener interface and set MediaPlayer in onSeekComplete method.
private MediaPlayer mediaPlayer;
#Override
public void onSeekComplete(final MediaPlayer mp) {
mediaPlayer = mp;
}
I was facing this issue yesterday and I'd like to share my experience facing this issue, the root cause and the fix in my particular issue; this might be helpful for someone else.
This is what I found in my particular issue.
I´m running MediaPlayer in Fragment
When the phone goes to sleep (black screen), in the fragment-life-cycle the stop() function is call.
MediaPlayer recommends to release() MediaPlayer resources on STOP state.
When the phone resumes, it complains with illegal-state-exception because there are no MediaPlayer resource available, remember it was released in the STOPE state.
So, to fix it. I overrided start() state and I got another instance of MediaPlayer if it was null at that specific point in time. START state is called at resume time.
sample code
public class xMediaPlayer extends MediaPlayer
{
private static xMediaPlayer instance = null;
public static xMediaPlayer getInstance( )
{
if( instance == null )
instance = new xMediaPlayer( );
return instance;
}
}
Override start() on fragment
#Override
public void onStart() {
super.onStart();
mMediaPlayer = xMediaPlayer.getInstance( );
}
My activity is playing mp3 file while is active, and my intention is to pause it while app takes user to another activity and resume when this activity is again active. Solution that was here around seems to be the right one but unfortunately id doesn't work, the audio file every time starts from beginning. My code is obvious:
private int length;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
mediaPlayer = new MediaPlayer();
mediaPlayer = MediaPlayer.create(this, R.raw.bensound_thejazzpiano);
mediaPlayer.setLooping(true);
mediaPlayer.setVolume(0.4f,0.4f);
mediaPlayer.start();
}
#Override
protected void onPause() {
super.onPause();
mediaPlayer.stop();
length = mediaPlayer.getCurrentPosition();
}
#Override
protected void onResume() {
super.onResume();
mediaPlayer.seekTo(length);
mediaPlayer.start();
}
I would also be satisfied with methods that mutes sound and restores the volume after goin back to activity (and muted tune can go on in background), but replacing start/stop methods with setVolume also doesn't provide to any results...
Maybe there are wrong methods I've overridden?
You have to "pause"(not stop) the mediaplayer in onPause, then start in onResume. That worked for me.
I only want to have background music in my first activity (MainActivity). When I Change to the next activity after clicking on a button, I want the music to stop. Is the the following code is enough, or do I have to implement the button, too?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = MediaPlayer.create(MainActivity.this, R.raw.music);
mp.setLooping(true);
mp.start();
add the onPause() method in your first activity, and pause/stop the music :)
#Override
public void onPause() {
if(mp.isPlaying()){
mp.pause();
//mp.stop();
}
super.onPause();
}
and even you can use the onResume() method to start again the music.
#Override
protected void onResume() {
mp.start();
super.onResume();
}
You'll need to make sure to stop the music when another activity launches. If you want it to start again if they return to this activity, you'll need to code that, likely by using startActivityForResult and activating it on result. Do you want it to play even if they hit the home button and hide the activity? If not, the easiest thing to do it start it in onResume and pause it in onPause.
Hi All I have got a video set as a background in my app. When the app starts the video plays at the main menu and everything works great. Now when I select to go to next activity the video stop and the next activity starts and when the user is then finished with this activity and presses the back button to go to go to the main menu the video should play again, however it doesn't. Hope some one can help me with this. here is my code:
public class MainActivity extends Activity {
VideoView animation;
private MediaController mc;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = MediaPlayer.create(this, R.raw.leftbanktwo);
mp.setLooping(true);
VideoView animation = (VideoView) findViewById(R.id.imageAnimation);
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/"+R.raw.cartoon);
mc = new MediaController(this);
animation.setMediaController(mc);
animation.requestFocus();
animation.setVideoURI(uri);
animation.start();
}
This is because your onCreate() method is not called again when user back to first Activity. If you want it to work like you described put the code which starts video in onResume() method.
Also, I would recommend to check out Activity Lifecycle.
Try This
#Override
protected void onResume() {
super.onResume();
if(mp!=null){
mp.reset();
mp.start();
}
}
#Override
protected void onPause() {
super.onPause();
if(mp!=null && mp.isPlaying()){
mp.pause();
}
}
I am new in android and I have another (simple?) problem. I don't know how to stop Media Player. This is my simple code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
MediaPlayer mp;
mp = MediaPlayer.create(this, R.raw.sauronsound);
mp.setLooping(false);
mp.start();
#Override
protected void onDestroy()
{
// Stop play
super.onDestroy();
mp.stop();
}
}
After pressing back button app goes to my first activity but sound is on. When I leave an app it is on too. What should I do to turn off the sound?
As always excuse me for my poor English.
I solved the problem thanks to you Guys. Working code:
public class SauronEye extends Activity {
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
mp = MediaPlayer.create(this, R.raw.sound);
mp.setLooping(false);
mp.start();
// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(10000);
}
#Override
protected void onStop()
{
// Stop play
super.onStop();
mp.stop();
}
}
Is it correct (it works)? Thank you for helping me.
mp reference that you are using on onDestroy is different from the one you are using on onCreate. Move the MediaPlayer mp; line to outside the onCreate class.
Check this out http://developer.android.com/reference/android/media/MediaPlayer.html
You can call stop or pause based on your requirement.When you select back button your onpause would be called, in that method you can call mp.stop(), onDestroy would be called only when activity is completely destroyed
onDestroy is only called when the activity is killed by the system. Rather than placing it in onDestroy, you should put it in onPause(), which is what's called whenever your activity is moved to the background but remains in memory. (Which is what happens with a back button being pressed or leaving the app)
#Override
protected void onPause() {
super.onPause();
mp.stop();
}
you can call the override implements source codes really easily and add them each into your code. All you need to do is right click the insertion point where you want them and click on Source->Override/Implement Methods. It will bring up a dialog box and you click on the methods you need, try using ondestroy, onpause, onstop. For your code and after it implements each of them just add the following to each.
protected void onDestroy{
super.onDestroy();
mp.release();
}
protected void onStop{
super.onStop();
mp.stop();
}
protected void onPause{
super.onPause();
mp.pause();
}
Also if you want a little more with you soundcodes you can try this link
stealthcopters link or you can try this video series
cornboyzAndroid