Search code examples
androidandroid-mediaplayer

Not able to catch the IllegalStateException of MediaPlayer


My code looks like this:

MediaPlayer mp = new MediaPlayer();
mp.setDataSource( "http://.../abc.mp3" );
mp.setOnPreparedListener( ... mp.start(); ... );
mp.prepareAsync();

Real code has checked if mp is prepared before it starts. Mostly it works fine. But sometimes (if weak connection) it still encounters this error:

MediaPlayer: Error (-38,0)
MediaPlayerNative: start called in state 0, mPlayer(0x7424863b40)

So, I decided to catch it:

try {
    mp.start();
} catch (IllegalStateException e) {
    Toast.makeText(...).show();
} catch (Throwable e) {
    Toast.makeText(...).show();
}

But this code does not work, I cannot catch any exception, and that error still displayed in log cat.


Solution

  • I've tried hard to find out what is wrong. And I found that I didn't release the media players when the activity stops. Because the media players are still located in memory so after an exact number of times I restart the activity, the new media players cannot load. And in another activity I use SoundPool, it also cannot load more streams.

    @Override
    protected void onStop() {
        super.onStop();
    
        for (int i = 0; i < mediaPlayerMap.size(); i++) {
            int key = mediaPlayerMap.keyAt(i);
            MediaPlayer mp = mediaPlayerMap.get(key);
            if (mp != null) {
                mp.release();
                mp = null;
            }
        }
    }
    

    Logcat:

    E/AudioFlinger: no more track names available
    E/AudioFlinger: createTrack_l() initCheck failed -12; no control block?
    E/AudioTrack: AudioFlinger could not create track, status: -12
    E/SoundPool: Error creating AudioTrack
    

    Refs:

    SoundPool error: no more track names available

    https://groups.google.com/forum/#!msg/android-platform/tyITQ09vV3s/jwNdyI2-7iYJ