Reputation: 667
I want to create activity background music, but MediaPlayer
playing not repeatedly :(
Why my MediaPlayer
is not looping?
There is my code:
MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.tersetetete);
mediaPlayer = new MediaPlayer();
mediaPlayer.setVolume(8f, 8f);
mediaPlayer.setLooping(true);
mediaPlayer = MediaPlayer.create(this, R.raw.fon);
mediaPlayer.start();
}
Upvotes: 4
Views: 9686
Reputation: 17850
Replace mediaPlayer = new MediaPlayer();
with the line mediaPlayer = MediaPlayer.create(this, R.raw.fon);
that you wrote below.
You are having the issues because new MediaPlayer();
creates a new MediaPlayer
object on which you set Volume and Looping properties, but after that you're creating a new object with MediaPlayer.create(this, R.raw.fon);
and then you play the sound represented by that new object which doesn't have any looping property set to true nor any volume of 8f 8f.
Here's the full code you can use:
MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.tersetetete);
mediaPlayer = MediaPlayer.create(this, R.raw.fon);
mediaPlayer.setVolume(.8f, .8f);
mediaPlayer.setLooping(true);
mediaPlayer.start();
}
Upvotes: 5
Reputation: 453
I am on KITKAT and setlooping(true) was not working for me, so I made this changes and now it works...
MediaPlayer mMediaPlayer;
//Stop on going Music
AudioManager audiomanager = (AudioManager)context.getSystemService("audio");
if (audiomanager.isMusicActive())
{
Intent intent = new Intent("com.android.music.musicservicecommand");
intent.putExtra("command", "pause");
context.sendBroadcast(intent);
}
//Setting Max Volume
audiomanager.setStreamVolume(3, audiomanager.getStreamMaxVolume(3), 0);
mMediaPlayer = MediaPlayer.create(context.getApplicationContext(),R.raw.file);
mMediaPlayer.start();
//This did the trick
mMediaPlayer.setOnErrorListener(new android.media.MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mediaplayer, int i, int j)
{
return false;
}
});
mMediaPlayer.setLooping(true);
And to stop I have used.
mMediaPlayer.release();
Upvotes: 1