0

My Android app has a music file that I want it playing when the Main Activity is started and I want the music file to restart when it finishes. So, basically I want it to loop over and over until the user has moved to a different activity. Below is the class that starts the music file, but when the music is over, it does not restart ...

 import android.app.Activity;
 import android.content.Context;
 import android.media.AudioManager;
 import android.media.MediaPlayer;
 import android.os.Bundle;

public class MainMenu extends Activity{
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_menu); 

    MediaPlayer mPlayer = MediaPlayer.create(MainMenu.this, R.raw.mmt_menu);
    mPlayer.start();

    AudioManager manager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
    if(!manager.isMusicActive())
     {
         mPlayer.start();
     }
}
}

What do I need to do so that when the music stops it restarts again?

Thanks very much!

user3079872
  • 191
  • 1
  • 5
  • 15
  • 1
    Have you tried calling `setLooping(true)` on the MediaPlayer? – Mike M. Jan 07 '15 at 23:22
  • possible duplicate of [Media Player Looping : Android](http://stackoverflow.com/questions/9461270/media-player-looping-android) – Melquiades Jan 07 '15 at 23:29
  • Thank you very much both. I had not seen the previous question, I had not thought of the word looping! Anyway, thanks a lot it does now loop. – user3079872 Jan 07 '15 at 23:35

1 Answers1

2

Call the function:

MediaPlayer.setLooping(true|false)

on the mediaplayerObject after you called MediaPlayer.prepare()

Example:

Uri mediaUri = createUri(context, R.raw.media); // Audiofile in raw folder Mediaplayer mPlayer = new MediaPlayer(); mPlayer.setDataSource(context, mediaUri); mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mPlayer.prepare();

mPlayer.setLooping(true);

mPlayer.start();

facutopa
  • 76
  • 1
  • 10
  • Thank you! And how to stop on Back Pressed? I tried : public void onBackPressed() {MediaPlayer mPlayer = MediaPlayer.create(MainMenu.this, R.raw.mmt_menu); mPlayer.stop(); finish(); but it does not stop ... – user3079872 Jan 07 '15 at 23:44
  • @user3079872 The MediaPlayer that code creates is not the one that is playing, which is why the audio doesn't stop. Make the MediaPlayer you're starting in `onCreate()` a class member - i.e., declare it outside of a method - and call `stop()` on that. – Mike M. Jan 07 '15 at 23:47