Search code examples
javaandroidandroid-mediaplayer

Noise when restarting MediaPlayer


I have a MediaPlayer (.wav file) that sometimes needs to be repeated in rapid succession. If it's already playing, I restart it:

if (player.isPlaying()) {
    player.pause();
    player.seekTo(0);
}
player.start();

The problem is that when the MediaPlayer is interrupted at some random position, there's often a tiny but noticeable scratchy noise at the end.

One solution I've tried is to create an array of MediaPlayers that load the same wav file, cycle through them, never interrupt, and ignore the call if the current item is already playing (which happens rarely, and the missed call isn't noticed in the general barrage anyway).

MediaPlayer player = players.get(current);
if (!player.isPlaying())
    player.start();
if((++current) >= players.size())
    current = 0;

This gets rid of the noise, but the solution is kind of ugly. Is there a better way?


Solution

  • The noise is probably the waveform being cut mid-cycle. It can possibly be fixed with calls to setVolume before stopping and starting. Having multiple MediaPlayers isn't a terrible idea, but you may want to have a look at SoundPool.