Reputation: 1
this is my first app so this question/answer might be pretty basic. I currently have onPause(); , to stop the music playing when player leaves the screen. I've tried to do a similar thing but with onResume, so that the music plays again (backgroundMusic). Unfortunately this isn't working. It does work again when I press the reset button or go back to the home page and come back to the game page. But it just doesn't load as soon as the app is back on screen, like I would like it to.
My code excerpt follows;
package com.example.android.buttongame;
...
public class MainActivity extends AppCompatActivity {
...
MediaPlayer winningSound;
MediaPlayer buttonSound;
MediaPlayer backgroundMusic;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
Plays ticking background noise at the start of this activity. Set on a loop
*/
backgroundMusic = MediaPlayer.create(this, R.raw.ticking_background);
backgroundMusic.start();
backgroundMusic.setOnErrorListener(new android.media.MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mediaplayer, int i, int j)
{
return false;
}
});
backgroundMusic.setLooping(true);
}
@Override
public void onResume(){
super.onResume();
backgroundMusic.start();
}
public void onPause() {
super.onPause();
backgroundMusic.stop();
}
...
public void reset(View v) {
/*
Plays button sound
*/
buttonSound = MediaPlayer.create(MainActivity.this, R.raw.button_sound);
buttonSound.start();
/*
* Refreshes activity
*/
this.recreate();
}
... public void homePage (View view) {
/*
Stops background music
*/
backgroundMusic.stop();
/*
Plays button sound
*/
buttonSound = MediaPlayer.create(MainActivity.this, R.raw.button_sound);
buttonSound.start();
/*
Leads to home page
*/
Intent homePage = new Intent(this, HomePage.class);
startActivity(homePage);
}
}
Upvotes: 0
Views: 837
Reputation: 1648
At the place of backgroundMusic.stop()
, you should use backgroundMusic.pause()
then you will achieve what you are looking for.
Calling stop()
stops playback and causes a MediaPlayer
in the Started, Paused, Prepared or PlaybackCompleted state to enter the Stopped state.
Once in the Stopped state, playback cannot be started until prepare()
or prepareAsync()
are called to set the MediaPlayer
object to the Prepared state again.
Calling stop()
has no effect on a MediaPlayer
object that is already in the Stopped state.
Here is the documentation of MediaPlayer
that will help you to understand about its APIs.
https://developer.android.com/reference/android/media/MediaPlayer
Upvotes: 1