MediaPlayer

Added in 1.0.0
Deprecated in 1.3.0

public final class MediaPlayer extends SessionPlayer


A media player which plays MediaItems. The details on playback control and player states can be found in the documentation of the base class, SessionPlayer.

Topic covered here:

  1. Audio focus and noisy intent

Audio focus and noisy intent

By default, MediaPlayer handles audio focus and noisy intent with set to this player. You need to call setAudioAttributes set the audio attribute while in the PLAYER_STATE_IDLE.

Here's the table of automatic audio focus behavior with audio attributes.

Audio Attributes Audio Focus Gain Type Misc
USAGE_VOICE_COMMUNICATION_SIGNALLING AUDIOFOCUS_NONE
AUDIOFOCUS_GAIN Developers should specific a proper usage instead of USAGE_UNKNOWN
AUDIOFOCUS_GAIN_TRANSIENT
AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK
AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE
USAGE_ASSISTANCE_ACCESSIBILITY AUDIOFOCUS_GAIN_TRANSIENT if CONTENT_TYPE_SPEECH, AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK otherwise
null No audio focus handling, and sets the player volume to 0 Only valid if your media contents don't have audio
Any other AudioAttributes No audio focus handling, and sets the player volume to 0 This is to handle error

If an AudioAttributesCompat is not specified by setAudioAttributes, getAudioAttributes will return null and the default audio focus behavior will follow the null case on the table above.

For more information about the audio focus, take a look at Managing audio focus

Summary

Nested types

This class is deprecated.

androidx.media2 is deprecated.

This class is deprecated.

androidx.media2 is deprecated.

Constants

static final int

Informs that audio is not playing.

static final int

Bad interleaving means that a media has been improperly interleaved or not interleaved at all, e.g has all the video samples first then all the audio ones.

static final int

Update status in buffering a media source received through progressive downloading.

static final int

A new set of metadata is available.

static final int

The media cannot be seeked (e.g live stream)

static final int

Informs that video is not playing.

static final int

The player just pushed the very first video frame for rendering.

static final int

The video is too complex for the decoder: it can't decode frames fast enough.

static final int
NO_TRACK_SELECTED = -2147483648

This field is deprecated.

getSelectedTrack returns null instead of this value.

static final int

File or network related operation errors.

static final int

Bitstream is not conforming to the related coding standard or file spec.

static final int

Some operation takes too long to complete, usually more than 3-5 seconds.

static final int

Unspecified player error.

static final int

Bitstream is conforming to the related coding standard or file spec, but the media framework does not support the feature.

static final int

This mode is used with seekTo to move media position to a frame (not necessarily a key frame) associated with a media item that is located closest to or at the given time.

static final int

This mode is used with seekTo to move media position to a sync (or key) frame associated with a media item that is located closest to (in time) or at the given time.

static final int

This mode is used with seekTo to move media position to a sync (or key) frame associated with a media item that is located right after or at the given time.

static final int

This mode is used with seekTo to move media position to a sync (or key) frame associated with a media item that is located right before or at the given time.

Public constructors

Constructor to create a MediaPlayer instance.

Public methods

@NonNull ListenableFuture<SessionPlayer.PlayerResult>
addPlaylistItem(int index, @NonNull MediaItem item)

Adds the media item to the playlist at the index.

@NonNull ListenableFuture<SessionPlayer.PlayerResult>
attachAuxEffect(int effectId)

Attaches an auxiliary effect to the player.

void

Closes the player and relinquish underlying resources.

@NonNull ListenableFuture<SessionPlayer.PlayerResult>

Deselects the TrackInfo for the current media item.

@Nullable AudioAttributesCompat

Gets the AudioAttributesCompat that media player has.

int

Returns the audio session ID.

long

Gets the position for how much has been buffered, or UNKNOWN_TIME if unknown.

int

Returns the current buffering state of the player.

@Nullable MediaItem

Gets the current media item, which is currently playing or would be played with later play.

int

Gets the index of current media item in playlist.

long

Gets the current playback position.

long

Gets the duration of the current media item, or UNKNOWN_TIME if unknown.

float
int

Gets the next item index in the playlist.

@NonNull PlaybackParams

Gets the playback params, containing the current playback rate.

@FloatRange(from = 0.0, to = Float.MAX_VALUE, fromInclusive = false) float

Gets the actual playback speed to be used by the player when playing.

int

Gets the current player state.

float
@Nullable List<MediaItem>

Gets the playlist.

@Nullable MediaMetadata

Gets the playlist metadata.

int

Gets the previous item index in the playlist.

int

Gets the repeat mode.

@Nullable MediaPlayer.TrackInfo
getSelectedTrack(int trackType)

Returns the selected track for the given track type.

int

Gets the shuffle mode.

@Nullable MediaTimestamp

Gets current playback position as a MediaTimestamp.

@NonNull List<MediaPlayer.TrackInfo>

This method is deprecated.

Use getTracks instead.

@NonNull List<SessionPlayer.TrackInfo>

Gets the full list of selected and unselected tracks that the media contains.

@NonNull VideoSize

Returns the size of the video.

@NonNull ListenableFuture<SessionPlayer.PlayerResult>
movePlaylistItem(int fromIndex, int toIndex)

Moves the media item at fromIdx to toIdx in the playlist.

@NonNull ListenableFuture<SessionPlayer.PlayerResult>

Pauses playback.

@NonNull ListenableFuture<SessionPlayer.PlayerResult>

Starts or resumes playback.

@NonNull ListenableFuture<SessionPlayer.PlayerResult>

Prepares the media items for playback.

void

Register PlayerCallback to listen changes.

@NonNull ListenableFuture<SessionPlayer.PlayerResult>
removePlaylistItem(@IntRange(from = 0) int index)

Removes the media item from the playlist

@NonNull ListenableFuture<SessionPlayer.PlayerResult>

Replaces the media item at index in the playlist.

void

Resets MediaPlayer to its uninitialized state if not closed.

@NonNull ListenableFuture<SessionPlayer.PlayerResult>
seekTo(long position)

Seeks to the specified position.

@NonNull ListenableFuture<SessionPlayer.PlayerResult>
seekTo(long position, int mode)

Moves the media to specified time position by considering the given mode.

@NonNull ListenableFuture<SessionPlayer.PlayerResult>

This method is deprecated.

Use selectTrack instead.

@NonNull ListenableFuture<SessionPlayer.PlayerResult>

Selects the TrackInfo for the current media item.

@NonNull ListenableFuture<SessionPlayer.PlayerResult>

Sets the AudioAttributesCompat to be used during the playback of the media.

@NonNull ListenableFuture<SessionPlayer.PlayerResult>
setAudioSessionId(int sessionId)

Sets the audio session ID.

@NonNull ListenableFuture<SessionPlayer.PlayerResult>
setAuxEffectSendLevel(@FloatRange(from = 0, to = 1) float level)

Sets the send level of the player to the attached auxiliary effect.

@NonNull ListenableFuture<SessionPlayer.PlayerResult>

Sets a MediaItem for playback.

@NonNull ListenableFuture<SessionPlayer.PlayerResult>

Sets playback params using PlaybackParams.

@NonNull ListenableFuture<SessionPlayer.PlayerResult>
setPlaybackSpeed(
    @FloatRange(from = 0.0, to = Float.MAX_VALUE, fromInclusive = false) float playbackSpeed
)

Sets the playback speed.

@NonNull ListenableFuture<SessionPlayer.PlayerResult>
setPlayerVolume(@FloatRange(from = 0, to = 1) float volume)

Sets the volume of the audio of the media to play, expressed as a linear multiplier on the audio samples.

@NonNull ListenableFuture<SessionPlayer.PlayerResult>
setPlaylist(
    @NonNull List<MediaItem> list,
    @Nullable MediaMetadata metadata
)

Sets a list of MediaItem with metadata.

@NonNull ListenableFuture<SessionPlayer.PlayerResult>
setRepeatMode(int repeatMode)

Sets the repeat mode.

@NonNull ListenableFuture<SessionPlayer.PlayerResult>
setShuffleMode(int shuffleMode)

Sets the shuffle mode.

@NonNull ListenableFuture<SessionPlayer.PlayerResult>

Sets the Surface to be used as the sink for the video portion of the media.

@NonNull ListenableFuture<SessionPlayer.PlayerResult>

Skips to the next item in the playlist.

@NonNull ListenableFuture<SessionPlayer.PlayerResult>
skipToPlaylistItem(@IntRange(from = 0) int index)

Skips to the item in the playlist at the index.

@NonNull ListenableFuture<SessionPlayer.PlayerResult>

Skips to the previous item in the playlist.

void

Unregister the previously registered PlayerCallback.

@NonNull ListenableFuture<SessionPlayer.PlayerResult>

Updates the playlist metadata while keeping the playlist as-is.

Inherited Constants

From androidx.media2.common.SessionPlayer
static final int

Buffering state indicating the player is buffering but enough has been buffered for this player to be able to play the content.

static final int

Buffering state indicating the player is buffering, but the player is currently starved for data, and cannot play.

static final int

Buffering state indicating the player is done buffering, and the remainder of the content is available for playback.

static final int

Buffering state is unknown.

static final int

Media item index is invalid.

static final int

State when the player is in error state and cannot be recovered self.

static final int

State when the player is idle, and needs configuration to start playback.

static final int

State when the player's playback is paused

static final int

State when the player's playback is ongoing

static final int

Playing media list will be repeated.

static final int

Playback of the playing media group will be repeated.

static final int

Playback will be stopped at the end of the playing media list.

static final int

Playback of the current playing media item will be repeated.

static final int

Media list will be played in shuffled order.

static final int

Media group will be played in shuffled order.

static final int

Media list will be played in order.

static final long
UNKNOWN_TIME = -9223372036854775808

Value indicating the time is unknown

Inherited methods

From java.io.Closeable
abstract void
From androidx.media2.common.SessionPlayer
final @NonNull List<Pair<SessionPlayer.PlayerCallbackExecutor>>

Gets the callbacks with executors for subclasses to notify player events.

Constants

MEDIA_INFO_AUDIO_NOT_PLAYING

Added in 1.0.0
Deprecated in 1.3.0
public static final int MEDIA_INFO_AUDIO_NOT_PLAYING = 804

Informs that audio is not playing. Note that playback of the video is not interrupted.

See also
onInfo

MEDIA_INFO_BAD_INTERLEAVING

Added in 1.0.0
Deprecated in 1.3.0
public static final int MEDIA_INFO_BAD_INTERLEAVING = 800

Bad interleaving means that a media has been improperly interleaved or not interleaved at all, e.g has all the video samples first then all the audio ones. Video is playing but a lot of disk seeks may be happening.

See also
onInfo

MEDIA_INFO_BUFFERING_UPDATE

Added in 1.0.0
Deprecated in 1.3.0
public static final int MEDIA_INFO_BUFFERING_UPDATE = 704

Update status in buffering a media source received through progressive downloading. The received buffering percentage indicates how much of the content has been buffered or played. For example a buffering update of 80 percent when half the content has already been played indicates that the next 30 percent of the content to play has been buffered.

The extra parameter in onInfo is the percentage (0-100) of the content that has been buffered or played thus far.

See also
onInfo

MEDIA_INFO_METADATA_UPDATE

Added in 1.0.0
Deprecated in 1.3.0
public static final int MEDIA_INFO_METADATA_UPDATE = 802

A new set of metadata is available.

See also
onInfo

MEDIA_INFO_NOT_SEEKABLE

Added in 1.0.0
Deprecated in 1.3.0
public static final int MEDIA_INFO_NOT_SEEKABLE = 801

The media cannot be seeked (e.g live stream)

See also
onInfo

MEDIA_INFO_VIDEO_NOT_PLAYING

Added in 1.0.0
Deprecated in 1.3.0
public static final int MEDIA_INFO_VIDEO_NOT_PLAYING = 805

Informs that video is not playing. Note that playback of the audio is not interrupted.

See also
onInfo

MEDIA_INFO_VIDEO_RENDERING_START

Added in 1.0.0
Deprecated in 1.3.0
public static final int MEDIA_INFO_VIDEO_RENDERING_START = 3

The player just pushed the very first video frame for rendering.

See also
onInfo

MEDIA_INFO_VIDEO_TRACK_LAGGING

Added in 1.0.0
Deprecated in 1.3.0
public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700

The video is too complex for the decoder: it can't decode frames fast enough. Possibly only the audio plays fine at this stage.

See also
onInfo

NO_TRACK_SELECTED

Added in 1.0.0
Deprecated in 1.1.0
public static final int NO_TRACK_SELECTED = -2147483648

The return value of getSelectedTrack when there is no selected track for the given type.

See also
getSelectedTrack

PLAYER_ERROR_IO

Added in 1.0.0
Deprecated in 1.3.0
public static final int PLAYER_ERROR_IO = -1004

File or network related operation errors.

See also
onError

PLAYER_ERROR_MALFORMED

Added in 1.0.0
Deprecated in 1.3.0
public static final int PLAYER_ERROR_MALFORMED = -1007

Bitstream is not conforming to the related coding standard or file spec.

See also
onError

PLAYER_ERROR_TIMED_OUT

Added in 1.0.0
Deprecated in 1.3.0
public static final int PLAYER_ERROR_TIMED_OUT = -110

Some operation takes too long to complete, usually more than 3-5 seconds.

See also
onError

PLAYER_ERROR_UNKNOWN

Added in 1.0.0
Deprecated in 1.3.0
public static final int PLAYER_ERROR_UNKNOWN = 1

Unspecified player error.

See also
onError

PLAYER_ERROR_UNSUPPORTED

Added in 1.0.0
Deprecated in 1.3.0
public static final int PLAYER_ERROR_UNSUPPORTED = -1010

Bitstream is conforming to the related coding standard or file spec, but the media framework does not support the feature.

See also
onError

SEEK_CLOSEST

Added in 1.0.0
Deprecated in 1.3.0
public static final int SEEK_CLOSEST = 3

This mode is used with seekTo to move media position to a frame (not necessarily a key frame) associated with a media item that is located closest to or at the given time.

See also
seekTo

SEEK_CLOSEST_SYNC

Added in 1.0.0
Deprecated in 1.3.0
public static final int SEEK_CLOSEST_SYNC = 2

This mode is used with seekTo to move media position to a sync (or key) frame associated with a media item that is located closest to (in time) or at the given time.

See also
seekTo

SEEK_NEXT_SYNC

Added in 1.0.0
Deprecated in 1.3.0
public static final int SEEK_NEXT_SYNC = 1

This mode is used with seekTo to move media position to a sync (or key) frame associated with a media item that is located right after or at the given time.

See also
seekTo

SEEK_PREVIOUS_SYNC

Added in 1.0.0
Deprecated in 1.3.0
public static final int SEEK_PREVIOUS_SYNC = 0

This mode is used with seekTo to move media position to a sync (or key) frame associated with a media item that is located right before or at the given time.

See also
seekTo

Public constructors

MediaPlayer

Added in 1.0.0
Deprecated in 1.3.0
public MediaPlayer(@NonNull Context context)

Constructor to create a MediaPlayer instance.

Parameters
@NonNull Context context

A Context that will be used to resolve UriMediaItem.

Public methods

addPlaylistItem

Added in 1.0.0
Deprecated in 1.3.0
public @NonNull ListenableFuture<SessionPlayer.PlayerResultaddPlaylistItem(int index, @NonNull MediaItem item)

Adds the media item to the playlist at the index. Index equals to or greater than the current playlist size (e.g. MAX_VALUE) will add the item at the end of the playlist.

If index is less than or equal to the current index of the playlist, the current index of the playlist would be increased correspondingly.

On success, a SessionPlayer.PlayerResult would be returned with item added.

Parameters
int index

the index of the item you want to add in the playlist

@NonNull MediaItem item

the media item you want to add

attachAuxEffect

Added in 1.0.0
Deprecated in 1.3.0
public @NonNull ListenableFuture<SessionPlayer.PlayerResultattachAuxEffect(int effectId)

Attaches an auxiliary effect to the player. A typical auxiliary effect is a reverberation effect which can be applied on any sound source that directs a certain amount of its energy to this effect. This amount is defined by setAuxEffectSendLevel(). See setAuxEffectSendLevel.

After creating an auxiliary effect (e.g. android.media.audiofx.EnvironmentalReverb), retrieve its ID with getId and use it when calling this method to attach the player to the effect.

To detach the effect from the player, call this method with a null effect id.

This method must be called before setMediaItem and setPlaylist methods.

Parameters
int effectId

system wide unique id of the effect to attach

Returns
@NonNull ListenableFuture<SessionPlayer.PlayerResult>

a ListenableFuture which represents the pending completion of the command. SessionPlayer.PlayerResult will be delivered when the command completed.

On success, a SessionPlayer.PlayerResult is returned with the current media item when the command completed.

close

Added in 1.0.0
public void close()

Closes the player and relinquish underlying resources.

deselectTrack

public @NonNull ListenableFuture<SessionPlayer.PlayerResultdeselectTrack(@NonNull SessionPlayer.TrackInfo trackInfo)

Deselects the TrackInfo for the current media item.

The track must be a subtitle track, and no audio or video tracks can be deselected.

Note: getSelectedTrack returns the currently selected track per track type that can be deselected, but the list may be invalidated when onTracksChanged is called.

Parameters
@NonNull SessionPlayer.TrackInfo trackInfo

the track to be selected

Returns
@NonNull ListenableFuture<SessionPlayer.PlayerResult>

a ListenableFuture which represents the pending completion of the command

getAudioAttributes

Added in 1.0.0
Deprecated in 1.3.0
public @Nullable AudioAttributesCompat getAudioAttributes()

Gets the AudioAttributesCompat that media player has.

getAudioSessionId

Added in 1.0.0
Deprecated in 1.3.0
public int getAudioSessionId()

Returns the audio session ID.

Returns
int

the audio session ID. See setAudioSessionId. Note that the audio session ID is 0 if a problem occurred when the MediaPlayer was constructed or it is closed.

getBufferedPosition

Added in 1.0.0
Deprecated in 1.3.0
public long getBufferedPosition()

Gets the position for how much has been buffered, or UNKNOWN_TIME if unknown.

The position is the relative position based on the getStartPosition. So the position 0 means the start position of the MediaItem.

Returns
long

the buffered position in ms, or UNKNOWN_TIME if unknown

getBufferingState

Added in 1.0.0
Deprecated in 1.3.0
public int getBufferingState()

Returns the current buffering state of the player.

During the buffering, see getBufferedPosition for the quantifying the amount already buffered.

Returns
int

the buffering state, or BUFFERING_STATE_UNKNOWN if unknown

getCurrentMediaItem

Added in 1.0.0
Deprecated in 1.3.0
public @Nullable MediaItem getCurrentMediaItem()

Gets the current media item, which is currently playing or would be played with later play. This value may be updated when onCurrentMediaItemChanged or onPlaylistChanged is called.

Returns
@Nullable MediaItem

the current media item. Can be null only when the player is in PLAYER_STATE_IDLE and a media item or playlist hasn't been set.

getCurrentMediaItemIndex

Added in 1.0.0
Deprecated in 1.3.0
public int getCurrentMediaItemIndex()

Gets the index of current media item in playlist. This value would be updated when onCurrentMediaItemChanged or onPlaylistChanged is called.

Returns
int

the index of current media item. Can be INVALID_ITEM_INDEX when current media item is null or not in the playlist, and when the playlist hasn't been set.

getCurrentPosition

Added in 1.0.0
Deprecated in 1.3.0
public long getCurrentPosition()

Gets the current playback position.

The position is the relative position based on the getStartPosition. So the position 0 means the start position of the MediaItem.

Returns
long

the current playback position in ms, or UNKNOWN_TIME if unknown

getDuration

Added in 1.0.0
Deprecated in 1.3.0
public long getDuration()

Gets the duration of the current media item, or UNKNOWN_TIME if unknown. If the current MediaItem has either start or end position, then duration would be adjusted accordingly instead of returning the whole size of the MediaItem.

Returns
long

the duration in ms, or UNKNOWN_TIME if unknown

getMaxPlayerVolume

Added in 1.0.0
Deprecated in 1.3.0
public float getMaxPlayerVolume()
Returns
float

the maximum volume that can be used in setPlayerVolume.

getNextMediaItemIndex

Added in 1.0.0
Deprecated in 1.3.0
public int getNextMediaItemIndex()

Gets the next item index in the playlist. This value would be updated when onCurrentMediaItemChanged or onPlaylistChanged is called.

Returns
int

the index of next media item. Can be INVALID_ITEM_INDEX only when next media item does not exist or playlist hasn't been set.

getPlaybackParams

Added in 1.0.0
Deprecated in 1.3.0
public @NonNull PlaybackParams getPlaybackParams()

Gets the playback params, containing the current playback rate.

Returns
@NonNull PlaybackParams

the playback params.

getPlaybackSpeed

Added in 1.0.0
Deprecated in 1.3.0
public @FloatRange(from = 0.0, to = Float.MAX_VALUE, fromInclusive = false) float getPlaybackSpeed()

Gets the actual playback speed to be used by the player when playing. A value of 1.0f is the default playback value, and a negative value indicates reverse playback.

Note that it may differ from the speed set in setPlaybackSpeed.

Returns
@FloatRange(from = 0.0, to = Float.MAX_VALUE, fromInclusive = false) float

the actual playback speed

getPlayerState

Added in 1.0.0
Deprecated in 1.3.0
public int getPlayerState()

Gets the current player state.

Returns
int

the current player state

getPlayerVolume

Added in 1.0.0
Deprecated in 1.3.0
public float getPlayerVolume()
Returns
float

the current volume of this player to this player. Note that it does not take into account the associated stream volume.

getPlaylist

Added in 1.0.0
Deprecated in 1.3.0
public @Nullable List<MediaItemgetPlaylist()

Gets the playlist. It can be null if the playlist hasn't been set or it's reset by setMediaItem.

Returns
@Nullable List<MediaItem>

playlist, or null

getPlaylistMetadata

Added in 1.0.0
Deprecated in 1.3.0
public @Nullable MediaMetadata getPlaylistMetadata()

Gets the playlist metadata.

Returns
@Nullable MediaMetadata

metadata metadata of the playlist, or null if none is set

getPreviousMediaItemIndex

Added in 1.0.0
Deprecated in 1.3.0
public int getPreviousMediaItemIndex()

Gets the previous item index in the playlist. This value would be updated when onCurrentMediaItemChanged or onPlaylistChanged is called.

Returns
int

the index of previous media item. Can be INVALID_ITEM_INDEX only when previous media item does not exist or playlist hasn't been set.

getRepeatMode

Added in 1.0.0
Deprecated in 1.3.0
public int getRepeatMode()

Gets the repeat mode.

Returns
int

repeat mode

getSelectedTrack

Added in 1.0.0
Deprecated in 1.3.0
public @Nullable MediaPlayer.TrackInfo getSelectedTrack(int trackType)

Returns the selected track for the given track type. The return value is an element in the list returned by getTracks.

Returns
@Nullable MediaPlayer.TrackInfo

metadata corresponding to the track currently selected for playback; null is returned when there is no selected track for trackType or when trackType is not one of audio or video.

Throws
java.lang.IllegalStateException

if called after close

See also
getTracks

getShuffleMode

Added in 1.0.0
Deprecated in 1.3.0
public int getShuffleMode()

Gets the shuffle mode.

Returns
int

the shuffle mode

getTimestamp

Added in 1.0.0
Deprecated in 1.3.0
public @Nullable MediaTimestamp getTimestamp()

Gets current playback position as a MediaTimestamp.

The MediaTimestamp represents how the media time correlates to the system time in a linear fashion using an anchor and a clock rate. During regular playback, the media time moves fairly constantly (though the anchor frame may be rebased to a current system time, the linear correlation stays steady). Therefore, this method does not need to be called often.

To help users get current playback position, this method always anchors the timestamp to the current system time, so getAnchorMediaTimeUs can be used as current playback position.

Returns
@Nullable MediaTimestamp

a MediaTimestamp object if a timestamp is available, or null if no timestamp is available, e.g. because the media player has not been initialized.

See also
MediaTimestamp

getTrackInfo

Added in 1.0.0
Deprecated in 1.1.0
public @NonNull List<MediaPlayer.TrackInfogetTrackInfo()

getTracks

public @NonNull List<SessionPlayer.TrackInfogetTracks()

Gets the full list of selected and unselected tracks that the media contains. The order of the list is irrelevant as different players expose tracks in different ways, but the tracks will generally be ordered based on track type.

Returns
@NonNull List<SessionPlayer.TrackInfo>

list of tracks. The total number of tracks is the size of the list. If empty, an empty list would be returned.

getVideoSize

Added in 1.0.0
Deprecated in 1.3.0
public @NonNull VideoSize getVideoSize()

Returns the size of the video.

Returns
@NonNull VideoSize

the size of the video. The width and height of size could be 0 if there is no video or the size has not been determined yet. The PlayerCallback can be registered via registerPlayerCallback to receive a notification onVideoSizeChanged when the size is available.

movePlaylistItem

public @NonNull ListenableFuture<SessionPlayer.PlayerResultmovePlaylistItem(int fromIndex, int toIndex)

Moves the media item at fromIdx to toIdx in the playlist.

On success, a SessionPlayer.PlayerResult would be returned with item set.

Parameters
int fromIndex

the media item's initial index in the playlist

int toIndex

the media item's target index in the playlist

pause

Added in 1.0.0
Deprecated in 1.3.0
public @NonNull ListenableFuture<SessionPlayer.PlayerResultpause()

Pauses playback.

On success, this transfers the player state to PLAYER_STATE_PAUSED and a SessionPlayer.PlayerResult would be returned with the current media item when the command was completed. If it is called in PLAYER_STATE_IDLE or PLAYER_STATE_ERROR, it would be ignored and a SessionPlayer.PlayerResult would be returned with RESULT_ERROR_INVALID_STATE.

Returns
@NonNull ListenableFuture<SessionPlayer.PlayerResult>

a ListenableFuture representing the pending completion of the command

play

Added in 1.0.0
Deprecated in 1.3.0
public @NonNull ListenableFuture<SessionPlayer.PlayerResultplay()

Starts or resumes playback.

On success, this transfers the player state to PLAYER_STATE_PLAYING and a SessionPlayer.PlayerResult would be returned with the current media item when the command was completed. If it is called in PLAYER_STATE_IDLE or PLAYER_STATE_ERROR, it would be ignored and a SessionPlayer.PlayerResult would be returned with RESULT_ERROR_INVALID_STATE.

Returns
@NonNull ListenableFuture<SessionPlayer.PlayerResult>

a ListenableFuture representing the pending completion of the command

prepare

Added in 1.0.0
Deprecated in 1.3.0
public @NonNull ListenableFuture<SessionPlayer.PlayerResultprepare()

Prepares the media items for playback. Before calling this API, set media item(s) through either setMediaItem or setPlaylist, and set a display surface through setSurface when needed.

On success, this transfers the player state from PLAYER_STATE_IDLE to PLAYER_STATE_PAUSED and a SessionPlayer.PlayerResult would be returned with the prepared media item when the command completed. If it's not called in PLAYER_STATE_IDLE, it would be ignored and SessionPlayer.PlayerResult would be returned with RESULT_ERROR_INVALID_STATE.

Returns
@NonNull ListenableFuture<SessionPlayer.PlayerResult>

a ListenableFuture representing the pending completion of the command

registerPlayerCallback

Added in 1.0.0
Deprecated in 1.3.0
public void registerPlayerCallback(
    @NonNull Executor executor,
    @NonNull MediaPlayer.PlayerCallback callback
)

Register PlayerCallback to listen changes.

Parameters
@NonNull Executor executor

a callback Executor

@NonNull MediaPlayer.PlayerCallback callback

a PlayerCallback

Throws
java.lang.IllegalArgumentException

if executor or callback is null.

removePlaylistItem

Added in 1.0.0
Deprecated in 1.3.0
public @NonNull ListenableFuture<SessionPlayer.PlayerResultremovePlaylistItem(@IntRange(from = 0) int index)

Removes the media item from the playlist

On success, a SessionPlayer.PlayerResult would be returned with item removed.

Parameters
@IntRange(from = 0) int index

the index of the item you want to remove in the playlist

replacePlaylistItem

Added in 1.0.0
Deprecated in 1.3.0
public @NonNull ListenableFuture<SessionPlayer.PlayerResultreplacePlaylistItem(int index, @NonNull MediaItem item)

Replaces the media item at index in the playlist. This can be also used to update metadata of an item.

On success, a SessionPlayer.PlayerResult would be returned with item set.

Parameters
int index

the index of the item to replace in the playlist

@NonNull MediaItem item

the new item

reset

Added in 1.0.0
Deprecated in 1.3.0
public void reset()

Resets MediaPlayer to its uninitialized state if not closed. After calling this method, you will have to initialize it again by setting the media item and calling prepare.

Note that if the player is closed, there is no way to reuse the instance.

seekTo

Added in 1.0.0
Deprecated in 1.3.0
public @NonNull ListenableFuture<SessionPlayer.PlayerResultseekTo(long position)

Seeks to the specified position.

The position is the relative position based on the getStartPosition. So calling seekTo with 0 means the seek to the start position.

On success, a SessionPlayer.PlayerResult would be returned with the current media item when the command completed. If it's called in PLAYER_STATE_IDLE, it is ignored and a SessionPlayer.PlayerResult would be returned with RESULT_ERROR_INVALID_STATE.

Parameters
long position

the new playback position in ms. The value would be in the range of start and end positions defined in MediaItem.

Returns
@NonNull ListenableFuture<SessionPlayer.PlayerResult>

a ListenableFuture representing the pending completion of the command

seekTo

Added in 1.0.0
Deprecated in 1.3.0
public @NonNull ListenableFuture<SessionPlayer.PlayerResultseekTo(long position, int mode)

Moves the media to specified time position by considering the given mode.

There is at most one active seekTo processed at any time. If there is a to-be-completed seekTo, new seekTo requests will be queued in such a way that only the last request is kept. When current seekTo is completed, the queued request will be processed if that request is different from just-finished seekTo operation, i.e., the requested position or mode is different.

On success, a SessionPlayer.PlayerResult is returned with the current media item when the command completed.

Parameters
long position

the offset in milliseconds from the start to seek to. When seeking to the given time position, there is no guarantee that the media item has a frame located at the position. When this happens, a frame nearby will be rendered. The value should be in the range of start and end positions defined in MediaItem.

int mode

the mode indicating where exactly to seek to.

Returns
@NonNull ListenableFuture<SessionPlayer.PlayerResult>

a ListenableFuture which represents the pending completion of the command. SessionPlayer.PlayerResult will be delivered when the command completed.

selectTrack

Added in 1.0.0
Deprecated in 1.1.0
public @NonNull ListenableFuture<SessionPlayer.PlayerResultselectTrack(@NonNull MediaPlayer.TrackInfo trackInfo)

selectTrack

public @NonNull ListenableFuture<SessionPlayer.PlayerResultselectTrack(@NonNull SessionPlayer.TrackInfo trackInfo)

Selects the TrackInfo for the current media item.

If the player is in invalid state, RESULT_ERROR_INVALID_STATE will be reported with SessionPlayer.PlayerResult. If a player is in Playing state, the selected track is presented immediately. If a player is not in Playing state, it just marks the track to be played.

In any valid state, if it is called multiple times on the same type of track (ie. Video, Audio), the most recent one will be chosen.

The first audio and video tracks are selected by default if available, even though this method is not called.

Currently, tracks that return true for isSelectable can be selected via this method.

Parameters
@NonNull SessionPlayer.TrackInfo trackInfo

metadata corresponding to the track to be selected. A trackInfo object can be obtained from getTracks.

Returns
@NonNull ListenableFuture<SessionPlayer.PlayerResult>

a ListenableFuture which represents the pending completion of the command. SessionPlayer.PlayerResult will be delivered when the command completed.

See also
getTracks

setAudioAttributes

Added in 1.0.0
Deprecated in 1.3.0
public @NonNull ListenableFuture<SessionPlayer.PlayerResultsetAudioAttributes(@NonNull AudioAttributesCompat attributes)

Sets the AudioAttributesCompat to be used during the playback of the media.

You must call this method in PLAYER_STATE_IDLE in order for the audio attributes to become effective thereafter. Otherwise, the call would be ignored and SessionPlayer.PlayerResult would be returned with RESULT_ERROR_INVALID_STATE.

On success, a SessionPlayer.PlayerResult would be returned with the current media item when the command completed.

Parameters
@NonNull AudioAttributesCompat attributes

non-null AudioAttributes.

setAudioSessionId

Added in 1.0.0
Deprecated in 1.3.0
public @NonNull ListenableFuture<SessionPlayer.PlayerResultsetAudioSessionId(int sessionId)

Sets the audio session ID.

Parameters
int sessionId

the audio session ID. The audio session ID is a system wide unique identifier for the audio stream played by this MediaPlayer2 instance. The primary use of the audio session ID is to associate audio effects to a particular instance of MediaPlayer2: if an audio session ID is provided when creating an audio effect, this effect will be applied only to the audio content of media players within the same audio session and not to the output mix. When created, a MediaPlayer2 instance automatically generates its own audio session ID. However, it is possible to force this player to be part of an already existing audio session by calling this method.

This method must be called before setMediaItem and setPlaylist methods.

Returns
@NonNull ListenableFuture<SessionPlayer.PlayerResult>

a ListenableFuture which represents the pending completion of the command. SessionPlayer.PlayerResult will be delivered when the command completed.

On success, a SessionPlayer.PlayerResult is returned with the current media item when the command completed.

setAuxEffectSendLevel

Added in 1.0.0
Deprecated in 1.3.0
public @NonNull ListenableFuture<SessionPlayer.PlayerResultsetAuxEffectSendLevel(@FloatRange(from = 0, to = 1) float level)

Sets the send level of the player to the attached auxiliary effect. See attachAuxEffect. The level value range is 0 to 1.0.

By default the send level is 0, so even if an effect is attached to the player this method must be called for the effect to be applied.

Note that the passed level value is a raw scalar. UI controls should be scaled logarithmically: the gain applied by audio framework ranges from -72dB to 0dB, so an appropriate conversion from linear UI input x to level is: x == 0 -> level = 0, 0 level = 10^(72*(x-R)/20/R)

On success, a SessionPlayer.PlayerResult is returned with the current media item when the command completed.

Parameters
@FloatRange(from = 0, to = 1) float level

send level scalar

Returns
@NonNull ListenableFuture<SessionPlayer.PlayerResult>

a ListenableFuture which represents the pending completion of the command. SessionPlayer.PlayerResult will be delivered when the command completed.

setMediaItem

Added in 1.0.0
Deprecated in 1.3.0
public @NonNull ListenableFuture<SessionPlayer.PlayerResultsetMediaItem(@NonNull MediaItem item)

Sets a MediaItem for playback. Use this or setPlaylist to specify which items to play. If you want to change current item in the playlist, use one of skipToPlaylistItem, skipToNextPlaylistItem, or skipToPreviousPlaylistItem instead of this method.

When this is called multiple times in any states other than PLAYER_STATE_ERROR, it would override previous setMediaItem or setPlaylist calls.

It's recommended to fill MediaMetadata in MediaItem especially for the duration information with the key METADATA_KEY_DURATION. Without the duration information in the metadata, session will do extra work to get the duration and send it to the controller.

On success, a SessionPlayer.PlayerResult would be returned with item set.

Parameters
@NonNull MediaItem item

the descriptor of media item you want to play

Returns
@NonNull ListenableFuture<SessionPlayer.PlayerResult>

a ListenableFuture which represents the pending completion of the command

Throws
java.lang.IllegalArgumentException

if the given item is null.

setPlaybackParams

Added in 1.0.0
Deprecated in 1.3.0
public @NonNull ListenableFuture<SessionPlayer.PlayerResultsetPlaybackParams(@NonNull PlaybackParams params)

Sets playback params using PlaybackParams.

On success, a SessionPlayer.PlayerResult is returned with the current media item when the command completed.

Parameters
@NonNull PlaybackParams params

the playback params.

Returns
@NonNull ListenableFuture<SessionPlayer.PlayerResult>

a ListenableFuture which represents the pending completion of the command. SessionPlayer.PlayerResult will be delivered when the command completed.

setPlaybackSpeed

Added in 1.0.0
Deprecated in 1.3.0
public @NonNull ListenableFuture<SessionPlayer.PlayerResultsetPlaybackSpeed(
    @FloatRange(from = 0.0, to = Float.MAX_VALUE, fromInclusive = false) float playbackSpeed
)

Sets the playback speed. The default playback speed is 1.0f, and values less than or equals to 0.0f is not allowed.

On success, a SessionPlayer.PlayerResult would be returned with the current media item when the command completed.

Parameters
@FloatRange(from = 0.0, to = Float.MAX_VALUE, fromInclusive = false) float playbackSpeed

the requested playback speed

Returns
@NonNull ListenableFuture<SessionPlayer.PlayerResult>

a ListenableFuture representing the pending completion of the command

setPlayerVolume

Added in 1.0.0
Deprecated in 1.3.0
public @NonNull ListenableFuture<SessionPlayer.PlayerResultsetPlayerVolume(@FloatRange(from = 0, to = 1) float volume)

Sets the volume of the audio of the media to play, expressed as a linear multiplier on the audio samples.

Note that this volume is specific to the player, and is separate from stream volume used across the platform.

A value of 0.0f indicates muting, a value of 1.0f is the nominal unattenuated and unamplified gain. See getMaxPlayerVolume for the volume range supported by this player.

The default player volume is 1.0f.

On success, a SessionPlayer.PlayerResult is returned with the current media item when the command completed.

Parameters
@FloatRange(from = 0, to = 1) float volume

a value between 0.0f and getMaxPlayerVolume.

Returns
@NonNull ListenableFuture<SessionPlayer.PlayerResult>

a ListenableFuture which represents the pending completion of the command. SessionPlayer.PlayerResult will be delivered when the command completed.

setPlaylist

Added in 1.0.0
Deprecated in 1.3.0
public @NonNull ListenableFuture<SessionPlayer.PlayerResultsetPlaylist(
    @NonNull List<MediaItem> list,
    @Nullable MediaMetadata metadata
)

Sets a list of MediaItem with metadata. Use this or setMediaItem to specify which items to play.

This can be called multiple times in any states other than PLAYER_STATE_ERROR. This would override previous setMediaItem or setPlaylist calls.

Ensure uniqueness of each MediaItem in the playlist so the session can uniquely identity individual items. All MediaItems wouldn't be null as well.

It's recommended to fill MediaMetadata in each MediaItem especially for the duration information with the key METADATA_KEY_DURATION. Without the duration information in the metadata, session will do extra work to get the duration and send it to the controller.

On success, a SessionPlayer.PlayerResult would be returned with the first media item of the playlist when the command completed.

Parameters
@NonNull List<MediaItem> list

a list of MediaItem objects to set as a play list

Returns
@NonNull ListenableFuture<SessionPlayer.PlayerResult>

a ListenableFuture which represents the pending completion of the command

Throws
java.lang.IllegalArgumentException

if the given list is null or empty, or has duplicated media items.

setRepeatMode

Added in 1.0.0
Deprecated in 1.3.0
public @NonNull ListenableFuture<SessionPlayer.PlayerResultsetRepeatMode(int repeatMode)

Sets the repeat mode.

On success, a SessionPlayer.PlayerResult would be returned with the current media item when the command completed.

Parameters
int repeatMode

repeat mode

setShuffleMode

Added in 1.0.0
Deprecated in 1.3.0
public @NonNull ListenableFuture<SessionPlayer.PlayerResultsetShuffleMode(int shuffleMode)

Sets the shuffle mode.

On success, a SessionPlayer.PlayerResult would be returned with the current media item when the command completed.

Parameters
int shuffleMode

the shuffle mode

Returns
@NonNull ListenableFuture<SessionPlayer.PlayerResult>

a ListenableFuture representing the pending completion of the command

setSurface

Added in 1.0.0
public @NonNull ListenableFuture<SessionPlayer.PlayerResultsetSurface(@Nullable Surface surface)

Sets the Surface to be used as the sink for the video portion of the media.

A null surface will result in only the audio track being played.

If the Surface sends frames to a SurfaceTexture, the timestamps returned from getTimestamp will have an unspecified zero point. These timestamps cannot be directly compared between different media sources, different instances of the same media source, or multiple runs of the same program. The timestamp is normally monotonically increasing and is unaffected by time-of-day adjustments, but it is reset when the position is set.

On success, a SessionPlayer.PlayerResult is returned with the current media item when the command completed.

Parameters
@Nullable Surface surface

The Surface to be used for the video portion of the media.

Returns
@NonNull ListenableFuture<SessionPlayer.PlayerResult>

a ListenableFuture which represents the pending completion of the command. SessionPlayer.PlayerResult will be delivered when the command completed.

skipToNextPlaylistItem

Added in 1.0.0
Deprecated in 1.3.0
public @NonNull ListenableFuture<SessionPlayer.PlayerResultskipToNextPlaylistItem()

Skips to the next item in the playlist.

On success, a SessionPlayer.PlayerResult would be returned with the current media item when the command completed.

Returns
@NonNull ListenableFuture<SessionPlayer.PlayerResult>

a ListenableFuture representing the pending completion of the command

skipToPlaylistItem

Added in 1.0.0
Deprecated in 1.3.0
public @NonNull ListenableFuture<SessionPlayer.PlayerResultskipToPlaylistItem(@IntRange(from = 0) int index)

Skips to the item in the playlist at the index.

On success, a SessionPlayer.PlayerResult would be returned with the current media item when the command completed.

Parameters
@IntRange(from = 0) int index

the index of the item you want to play in the playlist

skipToPreviousPlaylistItem

Added in 1.0.0
Deprecated in 1.3.0
public @NonNull ListenableFuture<SessionPlayer.PlayerResultskipToPreviousPlaylistItem()

Skips to the previous item in the playlist.

On success, a SessionPlayer.PlayerResult would be returned with the current media item when the command completed.

Returns
@NonNull ListenableFuture<SessionPlayer.PlayerResult>

a ListenableFuture representing the pending completion of the command

unregisterPlayerCallback

Added in 1.0.0
Deprecated in 1.3.0
public void unregisterPlayerCallback(@NonNull MediaPlayer.PlayerCallback callback)

Unregister the previously registered PlayerCallback.

Parameters
@NonNull MediaPlayer.PlayerCallback callback

the callback to be removed

Throws
java.lang.IllegalArgumentException

if the callback is null.

updatePlaylistMetadata

Added in 1.0.0
Deprecated in 1.3.0
public @NonNull ListenableFuture<SessionPlayer.PlayerResultupdatePlaylistMetadata(@Nullable MediaMetadata metadata)

Updates the playlist metadata while keeping the playlist as-is.

On success, a SessionPlayer.PlayerResult swuld be returned with the current media item when the command completed.

Parameters
@Nullable MediaMetadata metadata

metadata of the playlist