user3079872
user3079872

Reputation: 191

how to play same music file over and over again in android

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!

Upvotes: 0

Views: 257

Answers (1)

facutopa
facutopa

Reputation: 76

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

Upvotes: 2

Related Questions