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.
Related
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.
i create an app, and in one layout (just call it layout A), i play the media player, then when i went to another layout (just call it Layout B), i want the sound from the Layout A is continue playing in Layout B, and when i went back to the Layout A, i also want the media player is still continuing the music that was played before.
In Layout A, i set this code in onCreate:
player = MediaPlayer.create(this, R.raw.sound);
if(!isMuted())
{
player.setLooping(true);
player.start();
}
...
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
Intent intent = new Intent(A.this, B.class);
stop=1;
startActivity(intent);
}
});
And this code:
#Override
protected void onPause()
{
super.onPause();
if (stop!=1)
{
//stop=1 if i go to another layout, for example when i want to go to Layout B
//if the device is automatically locked, i want the media player is paused and it resumed when i unlock the device, so i use stop!=1 to know whether the sound should be paused or not
player.pause();
length = player.getCurrentPosition();
}
}
#Override
protected void onResume()
{
super.onResume();
if(!isMuted())
{
//isMuted is method to know whether the sound is muted or not, if it isn't muted, then the sound is resumed
player.seekTo(length);
player.setLooping(true);
player.start();
}
}
In layout B, i used this code in onCreate:
player = MediaPlayer.create(this, R.raw.sound);
....
And this code:
protected void onPause()
{
super.onPause();
player.pause();
length = player.getCurrentPosition();
}
#Override
protected void onResume()
{
super.onResume();
if(!isMuted())
{
if(player.isPlaying())
{
}
else
{
player.seekTo(length);
player.setLooping(true);
player.start();
}
}
}
But this is the problem.
When i went to Layout B, the Media Player from Layout A and Media Player from Layout B is played in the same time, so the sound is played simultaneously at one time.
When i went back to the Layout A, the Media Player in Layout B is stopped and the Media Player in Layout A is stopped and played from the beginning again, it didn't continue the Media Player that was played before.
When the device is locked, the media player is still played although i have used the indicator whether is should be paused or not. Any correction to the code?
I would recommend that you use a Service to play and pause/stop your music. It is not recommended to use Activity to handle music that way. You can start a Service and then play music in it. Services run in background and don't get destroyed automatically too often as compared to Activity. Here's a sample app code that does similar to what you need media player sound continue in all activities
In Activity MediaPlayer can play far.
You should use Service to play MediaPlayer and control from anywhere in application.
I used this tutorial.
https://thenewcircle.com/s/post/60/servicesdemo_using_android_service
In my Activity I have the following:
private Set<MediaPlayer> mediaPlayers;
public void onSomeEventInMyActivity()
{
// play sound
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.my_sound);
mediaPlayers.add(mediaPlayer);
mediaPlayer.setOnCompletionListener(new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
mp.release();
mediaPlayers.remove(mp);
}
});
mediaPlayer.start();
}
#Override
protected void onStart()
{
super.onStart();
mediaPlayers = new HashSet<MediaPlayer>();
}
#Override
protected void onStop()
{
super.onStop();
for (MediaPlayer mediaPlayer : mediaPlayers)
{
if (mediaPlayer.isPlaying())
{
mediaPlayer.stop();
}
mediaPlayer.release();
}
}
Is this code sufficient or will it lead to MediaPlayer leakage? Are my implementations of onStop and onStart necessary, or can I just rely on calling release in onCompletion?
I did my code this way because I assume onStop() could be called while a MediaPlayer is playing, so I need to call release because onCompletion won't be called yet. I'm just guessing that this is right, so correct me if I am wrong.
I also read that onStop is not called in low-memory situations - what to do then?
An onStop() routine is needed if the mediaPlayer is expected to stop when the activity becomes invisible. Otherwise, the mediaPlayer goes on playing. On older OSs, Gingerbread and earlier, the activity can execute onPause() - say, when a phone call arrives - and, in extreme circumstances, be destroyed without ever executing onStop(). I don't know what would happen to a running mediaPlayer then. However, if there is a phone call coming in, it might be an idea to stop the mediaPlayer in onPause()! Later OSs always pass through onStop() before destroying the Activity. Calling mp.release() on the mediaPlayer after stopping it, in either onPause() or onStop(), is correct.
It's also desirable to remove the reference to the player held in mediaPlayers, which doesn't happen in onStop() above. Something like:
#Override public void onCompletion(MediaPlayer mp) {
mp.stop(); // It's always safe to call stop()
mp.release(); // release resources internal to the MediaPlayer
mediaPlayers.remove(mp); // remove reference to MediaPlayer to allow GC
}
and then
#Override public void onPause() {
for (Object mediaPlayer : mediaPlayers.toArray()) {
onCompletion((MediaPlayer) mediaPlayer); // stop, release, and free for GC, each mp.
}
super.onPause();
}
(I originally had for (Object mediaPlayer : mediaPlayers) {} in the above code but omfeddf345mnof32nisd45fgoq2t pointed out that I would be modifying a set while iterating over it. Thanks for the correction!)
Only callback guaranted to be called is onPause(), so you may leak this media player in some situations. In case stopping player on activity pause is not acceptable you should use service, and watch for certain events ( like incoming phone call etc )
I have an android app where in my Main activity I can play music onCreate(), pause music onPause() and restart music onResume(). I am using MediaPlayer. The problem is that I don't want the music to restart onResume() when I'm rotating the screen on my Main activity. I only want the music to restart when I'm coming back to my Main activity from another activity. Any suggestions?
private MediaPlayer mp;
mp = MediaPlayer.create(MainActivity.this, R.raw.always_sunny);
mp.setLooping(true);
mp.start();
#Override
protected void onPause() {
super.onPause();
mp.getCurrentPosition();
mp.pause();
}
#Override
protected void onResume() {
super.onResume();
mp.seekTo(0);
mp.start();
}
Add the following attribute to the activity in the manifest:
android:configChanges="keyboardHidden|orientation|screenSize"
This would avoid that the activity restarts on orientation changes or when the keyboard appears.
If you need to do something when the rotation changes (for example, change an image in your case), add the following method to your activity:
#Override
public void onConfigurationChanged (Configuration newConfig) {
// Change here your image
}
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