android mediaplayer loops forever on ICS

一曲冷凌霜 提交于 2019-12-12 07:58:29

问题


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

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/10770752/android-mediaplayer-loops-forever-on-ics

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!