Load a media resource inside the MediaPlayer

One way of loading a media resource is to directly instantiate a MediaResource and load the video content to be played.

Loading a MediaResource is an asynchronous multiple-step process.



  1. Replace the MediaPlayer's currently playable item by calling MediaPlayer.replaceCurrentItem, passing an existing MediaResource instance.

    This starts the resource loading process.

  2. Register an implementation of the MediaPlayer.PlaybackEventListener interface with the MediaPlayer instance. Check for at least the following callbacks:
    • onPrepared

    • onStateChanged, and check for INITIALIZED and ERROR

    Through this event listener, the MediaPlayer object can notify your application when the media resource is successfully loaded.
  3. When the media player state changes to INITIALIZED, you can call MediaPlayer.prepareToPlay.

    This state indicates that the media has successfully loaded. Calling prepareToPlay starts the advertising resolution and placement process.

  4. When the PSDK calls the onPrepared callback, the media stream has successfully loaded and is prepared for playback.
In case of failure, the MediaPlayer switches to the ERROR state and notifies your application by calling your PlaybackEventListener.onStateChanged callback. The PSDK passes several parameters, including these:
  • A state parameter of type MediaPlayer.PlayerState with the value of MediaPlayer.PlayerState.ERROR.
  • A notification parameter of type MediaPlayerNotification that contains diagnostic information about the error event.

The following simplified sample code illustrates the process of loading a media resource:

// mediaResource is a properly configured MediaResource instance
// mediaPlayer is a MediaPlayer instance
// register a PlaybackEventListener implementation with the MediaPlayer instance
mediaPlayer.addEventListener(MediaPlayer.Event.PLAYBACK,
new MediaPlayer.PlaybackEventListener() {
@Override
public void onPrepared() {
// at this point, the resource is successfully loaded and available
// and the MediaPlayer is ready to start the playback
// once the resource is loaded, the MediaPlayer is able to
// provide a reference to the current "playable item"
MediaPlayerItem playerItem = mediaPlayer.getCurrentItem();
if (playerItem != null) {
    // here we can take a look at the properties of the
    // loaded stream
}
}
@Override
public void onStateChanged(MediaPlayer.PlayerState state,
    MediaPlayerNotification notification) {
if (state == MediaPlayer.PlayerState.ERROR) {
    // something bad happened - the resource cannot be loaded
   // details about the problem are provided via the MediaPlayerNotification instance
}else
if (state == MediaPlayer.PlayerState.INITIALIAZED) {
    mediaPlayer.prepareToPlay();
}
}
// implementation of the other methods in the PlaybackEventListener interface
...
}