Skip to content Skip to sidebar Skip to footer

Mediaplayer Prepare Showing Illegal State Exception

I am trying to play an audio file from the internal storage. The code I used is.. package com.abhi.firstapp.firstapp; import android.content.Context; import android.media.AudioMan

Solution 1:

There are a couple of things you might want to change.

First: mp.prepare() will block your main thread, which is forbidden and will result in an exception where Android will close your app. To prevent this, mp.prepareAsync was designed. Use that method instead and implement both an onPreparedListener and an onErrorListener.

Second: you should provide a datasource before you call prepare().

You could do this for example this way:

publicclassMainActivityextendsAppCompatActivityimplementsMediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener {

    protectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ...

        MediaPlayermp=newMediaPlayer();
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);

        try { 
            mediaPlayer.setDataSource(streamURL);
        } catch (IOException e) {
            // Error, do something
        }

        mp.prepareAsync();
        ...
    }
        @OverridepublicvoidonPrepared(MediaPlayer player) {
        mediaPlayer.start();
    }

    ...

}

Solution 2:

I had the same problem. It can be raised because MediaPlayer is already prepared. When you create a new MediaPlayer by MediaPlayer mp = MediaPlayer.create(getContext(),someUri); mp prepares automatically so you should not prepare it by yourself.

Post a Comment for "Mediaplayer Prepare Showing Illegal State Exception"