Cannot get android MediaPlayer onCompletion to fire

Andrew picture Andrew · Apr 3, 2012 · Viewed 11.4k times · Source

I'm trying to use the android MediaPlayer class to play some sounds.

Here's the code

MediaPlayer mp = new MediaPlayer(); 
mp.setDataSource(context, Uri.parse(soundUrl)); 
mp.setAudioStreamType(AudioManager.STREAM_MUSIC); 
mp.setLooping(false); 
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { 
    @Override 
            public void onCompletion(MediaPlayer mp) { 
                Log.i(LOGTAG, "onComplete hit"); 
                mp.stop(); 
                mp.release(); 
            } 
    });         

mp.prepare(); 
mp.start();

This code runs in a service, but for some reason the sound plays ok, but anything placed into the onCompletion doesn't seem to fire. I then get a message in the logcat that the mediaplayer wasn't released. I'm at a loss to what I've got wrong with this.

I'm running this testing on a galaxy nexus 4.0.4 stock rom.

I also notice that the sound can get clipped at the end.

Answer

ajacian81 picture ajacian81 · Oct 24, 2013

It's actually simple (but silly). Set your listener after you call start(), like so:

ediaPlayer mp = new MediaPlayer(); 
mp.setDataSource(context, Uri.parse(soundUrl)); 
mp.setAudioStreamType(AudioManager.STREAM_MUSIC); 
mp.setLooping(false); 
mp.prepare(); 
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { 
    @Override 
            public void onCompletion(MediaPlayer mp) { 
                Log.i(LOGTAG, "onComplete hit"); 
                mp.stop(); 
                mp.release(); 
            } 
    });