Handle MediaPlayer exceptions from throwing infinite errors

420 views Asked by At

I've implemented a service for MediaPlayer so that I can continue playing even after minimizing the app. The problem is whenever the MediaPlayer fails to play a song (e.g. The file not exists or the MediaPlayer source path is wrong) it throws an common error,

Error (-38,0) start called in state 0

This one keeps running in an infinite loop and since its in a background service so it's difficult to prevent this occurance. In this scenario I want to force close the MediaPlayer and wait till MediaPlayer starts playing another song.

I've already tried,

if (mp! = null && mp.isPlaying()) {
        mp.release();
}

But this doesn't stops the MediaPlayer throwing errors after getting an exception. I would like to know what would be the best practice to prevent such exception. Any kind of help would be greatly appreciated.

1

There are 1 answers

1
Lalit Poptani On BEST ANSWER

You can handle the error using onErrorListener on your MediaPlayer, like

mp.setOnErrorListener(new OnErrorListener() {

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        // handle your error here like exit media player or show message
         or move to next song

        return true;
    }
});

Here, the main thing is to return true, if you return false then error will not be handled by you.