Boris
Boris

Reputation: 8951

Playing sound only once

I'm trying to play an alarm sound exactly once:

    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);

    final MediaPlayer mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setDataSource(ctx, notification);
    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
    mMediaPlayer.prepare();
    mMediaPlayer.setLooping(false);

    mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        public void onPrepared(MediaPlayer arg0) {
            mMediaPlayer.seekTo(0);
            mMediaPlayer.start();
        }
    });

But the sound plays endlessly, although 'setLooping' is set to false. What else can I do to make the sound not loop?

Upvotes: 2

Views: 2279

Answers (1)

TomerZ
TomerZ

Reputation: 635

The call:

mMediaPlayer.prepare();

Is a blocking call for files so you dont really need the listener, you can just call:

mMediaPlayer.start();

Right after it. Also it start from time 0 so you dont need:

mMediaPlayer.seekTo(0);

As to the endless playing, you can find the explanation and solution here:

android mediaplayer loops forever on ICS

Upvotes: 2

Related Questions