Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android mediaplayer loops forever on ICS

I want to play a notification sound and my problem it that the sound loops forever, when it should sound only once.

I've tried two ways:

notification.sound = Uri.parse("content://media/internal/audio/media/38");

and

mMediaPlayer = new MediaPlayer();
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
mMediaPlayer.setDataSource(this, Uri.parse("content://media/internal/audio/media/38"));
mMediaPlayer.setLooping(false);
mMediaPlayer.prepare();
mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
    @Override
    public void onPrepared(MediaPlayer mp) {
        Log.v(Utils.TAG, "onprepared");
        mp.start();
    }
});

mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer mp) {
        Log.v(Utils.TAG, "end, we should release");
        mp.stop();
        mp.release();
    }
});

In the second case, I never see the trace "end, we should release", the audio is played over and over and over again.

Any idea?

Thank you very much

UPDATE:

I've tried two devices and:

  • It loops forever on a Galaxy Nexus with ICS 4.0.4
  • It works fine on a HTC Hero 2.2.1
like image 227
zegnus Avatar asked May 27 '12 00:05

zegnus


2 Answers

There are sounds with "built-in" loops which will play for ever. This is different to setting the MediaPlayer to looping. If you start playing a sound with a built-in loop, it will never finish. These are mostly ring tones (as opposed to alarm tones or notification tones). You can set the RingtoneManager to return only notification tones or alarm tones with myringtonemanager.setType(RingtoneManager.TYPE_ALARM|RingtoneManager.TYPE_NOTIFICATION) which will exclude most looping sounds, but unfortunaley this is not guaranteed to exclude them all on any device. :-(

Therefore the solution of Tiago Almeida is a good work-around (and i've voted it up) though it will also truncate all sounds which have just a few (and no infinite) loops.

like image 177
Kio_BuE Avatar answered Oct 13 '22 21:10

Kio_BuE


Try this:

try {
    mp.setDataSource(uri.toString());
    mp.setAudioStreamType(AudioManager.STREAM_ALARM);
    mp.prepare();
    mp.start();
    mp.setOnSeekCompleteListener(new OnSeekCompleteListener() {
        public void onSeekComplete(MediaPlayer mp) {
            mp.stop();
            mp.release();
        }
    });
} catch (Exception e) {
    e.printStackTrace();
}
like image 34
SangYoon Park Avatar answered Oct 13 '22 22:10

SangYoon Park