Search code examples
javaandroidmedia-player

Stop buffering data after some time with Media Player


I'm using Media Player to streamming. Sometimes because the connection is slow or because others factors the buffering is taken too much time to call the onPrepared method. I would like to stop buffering data after some time in Media Player.

For example:

public void play() {
     try{
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setDataSource(source);
        mMediaPlayer.prepareAsync();
    } catch (Exception e) {
       // ....
    }
}

@Override
public void onPrepared(MediaPlayer arg0) {

    // Send a message to activity to end progress dialogue
    sendBufferCompleteBroadcast();
    playMedia();

}

What could be the best way to do it?


Solution

  • I added call the following method after mMediaPlayer.prepareAsync().

    // Prevent Media Player taking so long time
        private void postDelayed() {
    
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                public void run() {
                    mMediaPlayer.reset();
                }}, 5000);  // 5 seconds
    
        }
    

    If after 5 seconds I don't get a response the mediaplayer is reset.