onResume to restart playing background music is not working - java

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

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

Related

Adding music in android studio (java, MediaPlayer)

buttonMusic = findViewById(R.id.buttonMus);
musicSound = MediaPlayer.create(this, R.raw.music);
buttonClick();
}
private Button buttonMusic;
private MediaPlayer musicSound;
public void buttonClick() {
buttonMusic.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
soundPlay(musicSound);
}
}
);
}
public void soundPlay(MediaPlayer sound) {
if (sound.isPlaying()) {
sound.stop();
}else {
sound.start();
sound.setLooping(true);
} }
Hello.
The code launches the music, is able to stop it, but it wont play again after pressing the play button, after pausing the song that is.
you aren't pausing song, you are stop()ing it. use sound.pause() for pausing :)
after stop() MediaPlayer you have to prepare it again, use prepare() or prepareAsync(). MediaPlayer.create( makes that for you at the beginning, also if you would create MediaPlayer using its constructor you would also want to prepare()/preapreAsync() before calling start() in onClick
check out state diagram of MediaPlayer

Android: Media Player not pausing in second activity using ImageView

I have spent almost the day trying to figure it out and yet could not manage to achieve it. I basically have two activities, MainActivity.java and GameActivity.java. The music stops but after going back to MainActivity.java and coming back to GameActivity.java using ImageView several times.
MainActivity.java
public class MainActivity extends AppCompatActivity {
ImageView iv;
public static final String BG_SOUND_CHECK = "background playing!";
// public static MediaPlayer backgroundSound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Handler handler = new Handler();
final MediaPlayer backgroundSound = MediaPlayer.create(this, R.raw.background_music);
handler.postDelayed(new Runnable() {
#Override
public void run() {
backgroundSound.setLooping(true);
backgroundSound.start();
Log.v(BG_SOUND_CHECK, "After loop Started!");
}
}, 3000);
getSupportActionBar().hide();
iv = (ImageView)findViewById(R.id.playImage);
iv.setOnClickListener(new View.OnClickListener(){
public void onClick(View view1){
// backgroundSound.setLooping(false);
backgroundSound.pause();
// Log.v(BG_SOUND_CHECK, "Playing After Play Button Click");
Intent myIntent = new Intent(MainActivity.this, GameActivity.class);
// myIntent.putExtra("backgroundSoundObj",backgroundSound);
startActivity(myIntent);
// Log.v(BG_SOUND_CHECK, "After Game Scene");
}
});
}
}
GameActivity.java
public class GameActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
// MainActivity.backgroundSound.pause();
// Rest of the code
}
}
I tried putting the music onPause(); in
1) ImageView onClick();
2) As soon as the GameActivity.java is loaded
but both ways end up pausing it only after I try coming back to MainActivity.java and going to GameActivity.java several times.
Do you see how you put your backgroundSound.start() inside the postDelayed-3000 ?
backgroundSound.pause() anytime before that 3000ms is not going to do anything.
It has nothing to do with going back and forth between your two activities, it just so happens that doing that takes up more than 3000ms, so when you do click for pause(), 3000ms has passed.
What you can do, to fit your current code, is to separate that into a Runnable.
Runnable bgSound = new Runnable() {
#Override
public void run() {
backgroundSound.setLooping(true);
backgroundSound.start();
Log.v(BG_SOUND_CHECK, "After loop Started!");
}
}
Use it with handler.postDelayed(bgSound, 3000)
In your onClick, if you want to stop it from playing before it starts, can use handler.removeCallbacks(bgSound), to stop it after it plays, your pause(). If you don't care to know if it has or hasn't started, you can do both alongside each other, should work fine too.
(if you don't want the music to play after you've left your main activity, you should also do the same actions in your onDestroy and/or onPause)

cant pause mediaplayer after reopen activity

Here in my MainActivity.java I have an object MediaPlayer, which plays a sound when you click playB button and pause by pressing pauseB. Everything is working fine. But if you re-open the app and click pauseB, the sound continues to play. How to fix it? How to catch the current playing MediaPlayer?
public class MainActivity extends ActionBarActivity {
Button playB;
Button pauseB;
Context c;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button playB = (Button) findViewById(R.id.playB);
Button pauseB = (Button) findViewById(R.id.pauseB);
mp = mp.create(this, R.raw.fawaid_1);
playB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mp.start();
}
});
pauseB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mp.pause();
}
});
}
}
when you re-open the app, onCreate is called again, hence you have a new MediaPlayer object, and from that moment, play and pause buttons will control that new player object instead of a previous one. That's why your pause button will have no effect on the sound that started BEFORE you minimized the app. And if you press play button now, you will have two sounds playing at the same time
one way to overcome this, is to check if media player has already been initialized:
if(mp==null)
mp = MediaPlayer.create(this, R.raw.fawaid_1);
It is advisable to use Service with AIDL in developing music player.
Reasons.
You can retain the control again once you go back in your activity.
It is easy to perform an inter process communication.
Here is a simple music Player that runs on the Background, Music Player
The song I used in this music player is Owned by SnowFlakes

Resume song in Android

I have created a media player . I run the application properly. But I want to resume my song when I restart my activity. Why does my audio restart when I restart my activity?
How can I do this? I don't understand. Can any one help me??
Here is my code.
public class Audio_Activity extends Activity {
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.audio);
init();
mp=MediaPlayer.create(Audio_Activity.this,R.raw.ennamo_yadho);
Log.e("Song is playing","in Mediya Player ");
if(mp!=null) {
length=mp.getCurrentPosition();
Log.e("Current ","Position -> " + length);
if(length > 0){
mp.seekTo(length);
mp.start();
btnChapter.setEnabled(false);
}
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.stop();
mp.release();
btnChapter.setEnabled(true);
System.out.println("Music is over and Button is enable !!!!!!");
}
});
}
}
To prevent this you should use a service for playing sounds while your activity goes to background. Refer to the android's documentation about the life-cycle of an activity to see what actually happens: https://developer.android.com/training/basics/activity-lifecycle/index.html
Can you try:
mp.start();
mp.seekTo(length);
Referring to documentation of MediaPlayer:
public void start ()
Starts or resumes playback. If playback had previously been paused, playback will continue from where it was paused. If playback had been stopped, or never started before, playback will start at the beginning.
Save the mp.getCurrentPosition in a persistence of some sort, sharedprefs for instance in onPause, call pause() on the mediaplayer.
In onResume, do mp.start(), mp.seekTo(savedPosition).

Android: Mediaplayer plays multiple times if I keep on pressing the back button and launch the app again

When I play my song and press the back button to return to return to home, the music continues playing. When I launch the app again, the music plays twice. I think it's the onResume method because I commented out the method and the problem stopped. How do I get onResume work properly? I tried using if(backgroundMusic.isplaying()) inside the onResume, but the app crashes when I resume from another activity. What am I doing wrong?
//global mediaplayer
MediaPlayer backgroundMusic;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
loadBackgroundMusic();
}
private void loadBackgroundMusic() {
//load mp3 into object and start it
backgroundMusic = MediaPlayer.create(this,R.raw.backgrounmusic);
backgroundMusic.setLooping(true);
backgroundMusic.start();
}
#Override
protected void onPause() {
super.onPause();
backgroundMusic.release();
}
#Override
protected void onResume() {
super.onResume();
loadBackgroundMusic();
}
#Override
protected void onStop() {
super.onStop();
backgroundMusic.release();
}
I'm not really sure about the behavior you want. As I see it, it's one of two:
Music should be played only while my Activity is visible
If this is the case, you should look closer on the documentation for the Activity Lifecycle. This will for example tell you that onResume() will also be called the first time the Activity is created.
So the solution would be to start the music in onResume() and stop on onPause() or similar.
After starting my activity once, music should be played even if i return to home screen
In this case you really want a Service.

Categories

Resources