Skip to content Skip to sidebar Skip to footer

Android Mediaplayer - Setdatasource And Release - Illegalstateexception

I wrote my own MediaPlayer class to play files at a specific path and to play files from the assets folder. Here is the class: public class CMediaPlayer extends MediaPlayer{ publi

Solution 1:

change mp.release(); to mp.reset();

public void reset ()

Resets the MediaPlayer to its uninitialized state. After calling this method, you will have to initialize it again by setting the data source and calling prepare().

public void release ()

Releases resources associated with this MediaPlayer object. It is considered good practice to call this method when you're done using the MediaPlayer. In particular, whenever an Activity of an application is paused (its onPause() method is called), or stopped (its onStop() method is called), this method should be invoked to release the MediaPlayer object, unless the application has a special need to keep the object around. In addition to unnecessary resources (such as memory and instances of codecs) being held, failure to call this method immediately if a MediaPlayer object is no longer needed may also lead to continuous battery consumption for mobile devices, and playback failure for other applications if no multiple instances of the same codec are supported on a device. Even if multiple instances of the same codec are supported, some performance degradation may be expected when unnecessary multiple instances are used at the same time.

You need to keep the object around.

You can do it in a simple way

MediaPlayermediaPlayer=newMediaPlayer();
        mediaPlayer.setDataSource(context, ringtone);
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MEDIA);
        mediaPlayer.prepare();
        mediaPlayer.start();

Solution 2:

me too i have this problem but i have used:

publicvoidplay(String name){
    try {
        AssetFileDescriptor afd = getAssets().openFd(name);
        if(myPlayer == null){
            myPlayer = newMediaPlayer();
        }
        myPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        myPlayer.prepare();
        myPlayer.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

and to stop:

publicvoidstopPlayer(){
    if(myPlayer!= null && myPlayer.isPlaying()){
        myPlayer.stop();
        myPlayer = null;
    }else{
        myPlayer = null;
    }
}

Post a Comment for "Android Mediaplayer - Setdatasource And Release - Illegalstateexception"