Search code examples
androidmedia-playerhttp-live-streaming

Live streaming through mediaplayer in android


How can I stream an online URL using MediaPlayer?


Solution

  • Basically, you need to do the following if you are using the Android MediaPlayer class:

    MediaPlayer mediaPlayer = new MediaPlayer();
    
    mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
        public boolean onError(MediaPlayer mp, int what, int extra) {
            mp.reset();
            return false;
        }
    });
    
    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        public void onPrepared(MediaPlayer mp) {
            mp.start();
        }
    });
    
    try {
        mediaPlayer.setDataSource("http://someurl");
        mediaPlayer.prepareAsync();
    } catch (IllegalArgumentException e) {
    } catch (IllegalStateException e) {
    } catch (IOException e) {
    }
    

    Keep in mind the Android MediaPlayer class will only play supported formats: http://developer.android.com/guide/appendix/media-formats.html