MediaPlayer

public final class MediaPlayer
extends SessionPlayer

java.lang.Object
   ↳ androidx.media2.common.SessionPlayer
     ↳ androidx.media2.player.MediaPlayer


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 AudioAttributesCompat set to this player. You need to call setAudioAttributes(AudioAttributesCompat) set the audio attribute while in the SessionPlayer.PLAYER_STATE_IDLE.

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

Audio AttributesAudio Focus Gain TypeMisc
AudioAttributesCompat.USAGE_VOICE_COMMUNICATION_SIGNALLING AudioManager.AUDIOFOCUS_NONE
AudioManager.AUDIOFOCUS_GAIN Developers should specific a proper usage instead of AudioAttributesCompat.USAGE_UNKNOWN
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE
AudioAttributesCompat.USAGE_ASSISTANCE_ACCESSIBILITY AudioManager.AUDIOFOCUS_GAIN_TRANSIENT if AudioAttributesCompat.CONTENT_TYPE_SPEECH, AudioManager.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(AudioAttributesCompat), 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 classes

class MediaPlayer.PlayerCallback

Interface definition for callbacks to be invoked when the player has the corresponding events. 

class MediaPlayer.TrackInfo

Class for the player to return each audio/video/subtitle track's metadata. 

Constants

int MEDIA_INFO_AUDIO_NOT_PLAYING

Informs that audio is not playing.

int MEDIA_INFO_BAD_INTERLEAVING

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.

int MEDIA_INFO_BUFFERING_UPDATE

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

int MEDIA_INFO_METADATA_UPDATE

A new set of metadata is available.

int MEDIA_INFO_NOT_SEEKABLE

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

int MEDIA_INFO_VIDEO_NOT_PLAYING

Informs that video is not playing.

int MEDIA_INFO_VIDEO_RENDERING_START

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

int MEDIA_INFO_VIDEO_TRACK_LAGGING

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

int NO_TRACK_SELECTED

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

int PLAYER_ERROR_IO

File or network related operation errors.

int PLAYER_ERROR_MALFORMED

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

int PLAYER_ERROR_TIMED_OUT

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

int PLAYER_ERROR_UNKNOWN

Unspecified player error.

int PLAYER_ERROR_UNSUPPORTED

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

int SEEK_CLOSEST

This mode is used with seekTo(long, int) 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.

int SEEK_CLOSEST_SYNC

This mode is used with seekTo(long, int) 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.

int SEEK_NEXT_SYNC

This mode is used with seekTo(long, int) 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.

int SEEK_PREVIOUS_SYNC

This mode is used with seekTo(long, int) 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.

Inherited constants

Public constructors

MediaPlayer(Context context)

Constructor to create a MediaPlayer instance.

Public methods

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

Adds the media item to the playlist at position index.

ListenableFuture<SessionPlayer.PlayerResult> attachAuxEffect(int effectId)

Attaches an auxiliary effect to the player.

void close()
AudioAttributesCompat getAudioAttributes()

Gets the AudioAttributesCompat that media player has.

int getAudioSessionId()

Returns the audio session ID.

long getBufferedPosition()

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

int getBufferingState()

Returns the current buffering state of the player.

MediaItem getCurrentMediaItem()

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

int getCurrentMediaItemIndex()

Gets the index of current media item in playlist.

long getCurrentPosition()

Gets the current playback head position.

long getDuration()

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

float getMaxPlayerVolume()
int getNextMediaItemIndex()

Gets the next item index in the playlist.

PlaybackParams getPlaybackParams()

Gets the playback params, containing the current playback rate.

float getPlaybackSpeed()

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

int getPlayerState()

Gets the current player state.

float getPlayerVolume()
List<MediaItem> getPlaylist()

Gets the playlist.

MediaMetadata getPlaylistMetadata()

Gets the playlist metadata.

int getPreviousMediaItemIndex()

Gets the previous item index in the playlist.

int getRepeatMode()

Gets the repeat mode.

MediaPlayer.TrackInfo getSelectedTrack(int trackType)

Returns the audio or video track currently selected for playback.

int getShuffleMode()

Gets the shuffle mode.

MediaTimestamp getTimestamp()

Gets current playback position as a MediaTimestamp.

List<MediaPlayer.TrackInfo> getTrackInfo()

Returns a List of track information.

VideoSize getVideoSize()

Returns the size of the video.

ListenableFuture<SessionPlayer.PlayerResult> pause()

Pauses playback.

ListenableFuture<SessionPlayer.PlayerResult> play()

Starts or resumes playback.

ListenableFuture<SessionPlayer.PlayerResult> prepare()

Prepares the media items for playback.

void registerPlayerCallback(Executor executor, MediaPlayer.PlayerCallback callback)

Register MediaPlayer.PlayerCallback to listen changes.

ListenableFuture<SessionPlayer.PlayerResult> removePlaylistItem(int index)

Removes the media item from the playlist

The implementation may not change the currently playing media item even when it's removed.

ListenableFuture<SessionPlayer.PlayerResult> replacePlaylistItem(int index, MediaItem item)

Replaces the media item at index in the playlist.

void reset()

Resets MediaPlayer to its uninitialized state if not closed.

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

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

ListenableFuture<SessionPlayer.PlayerResult> seekTo(long position)

Seeks to the specified position.

ListenableFuture<SessionPlayer.PlayerResult> selectTrack(MediaPlayer.TrackInfo trackInfo)

Selects a track.

ListenableFuture<SessionPlayer.PlayerResult> setAudioAttributes(AudioAttributesCompat attr)

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

ListenableFuture<SessionPlayer.PlayerResult> setAudioSessionId(int sessionId)

Sets the audio session ID.

ListenableFuture<SessionPlayer.PlayerResult> setAuxEffectSendLevel(float level)

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

ListenableFuture<SessionPlayer.PlayerResult> setMediaItem(MediaItem item)

Sets a MediaItem for playback.

ListenableFuture<SessionPlayer.PlayerResult> setPlaybackParams(PlaybackParams params)

Sets playback params using PlaybackParams.

ListenableFuture<SessionPlayer.PlayerResult> setPlaybackSpeed(float playbackSpeed)

Sets the playback speed.

ListenableFuture<SessionPlayer.PlayerResult> setPlayerVolume(float volume)

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

ListenableFuture<SessionPlayer.PlayerResult> setPlaylist(List<MediaItem> playlist, MediaMetadata metadata)

Sets a list of MediaItem with metadata.

ListenableFuture<SessionPlayer.PlayerResult> setRepeatMode(int repeatMode)

Sets the repeat mode.

ListenableFuture<SessionPlayer.PlayerResult> setShuffleMode(int shuffleMode)

Sets the shuffle mode.

ListenableFuture<SessionPlayer.PlayerResult> setSurface(Surface surface)

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

ListenableFuture<SessionPlayer.PlayerResult> skipToNextPlaylistItem()

Skips to the next item in the playlist.

ListenableFuture<SessionPlayer.PlayerResult> skipToPlaylistItem(int index)

Skips to the the media item.

ListenableFuture<SessionPlayer.PlayerResult> skipToPreviousPlaylistItem()

Skips to the previous item in the playlist.

void unregisterPlayerCallback(MediaPlayer.PlayerCallback callback)

Unregister the previously registered MediaPlayer.PlayerCallback.

ListenableFuture<SessionPlayer.PlayerResult> updatePlaylistMetadata(MediaMetadata metadata)

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

Inherited methods

Constants

MEDIA_INFO_AUDIO_NOT_PLAYING

public static final int MEDIA_INFO_AUDIO_NOT_PLAYING

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

Constant Value: 804 (0x00000324)

MEDIA_INFO_BAD_INTERLEAVING

public static final int MEDIA_INFO_BAD_INTERLEAVING

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.

Constant Value: 800 (0x00000320)

MEDIA_INFO_BUFFERING_UPDATE

public static final int MEDIA_INFO_BUFFERING_UPDATE

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 MediaPlayer.PlayerCallback.onInfo(MediaPlayer, MediaItem, int, int) is the percentage (0-100) of the content that has been buffered or played thus far.

Constant Value: 704 (0x000002c0)

MEDIA_INFO_METADATA_UPDATE

public static final int MEDIA_INFO_METADATA_UPDATE

A new set of metadata is available.

Constant Value: 802 (0x00000322)

MEDIA_INFO_NOT_SEEKABLE

public static final int MEDIA_INFO_NOT_SEEKABLE

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

Constant Value: 801 (0x00000321)

MEDIA_INFO_VIDEO_NOT_PLAYING

public static final int MEDIA_INFO_VIDEO_NOT_PLAYING

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

Constant Value: 805 (0x00000325)

MEDIA_INFO_VIDEO_RENDERING_START

public static final int MEDIA_INFO_VIDEO_RENDERING_START

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

Constant Value: 3 (0x00000003)

MEDIA_INFO_VIDEO_TRACK_LAGGING

public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING

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

Constant Value: 700 (0x000002bc)

NO_TRACK_SELECTED

public static final int NO_TRACK_SELECTED

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

Constant Value: -2147483648 (0x80000000)

PLAYER_ERROR_IO

public static final int PLAYER_ERROR_IO

File or network related operation errors.

Constant Value: -1004 (0xfffffc14)

PLAYER_ERROR_MALFORMED

public static final int PLAYER_ERROR_MALFORMED

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

Constant Value: -1007 (0xfffffc11)

PLAYER_ERROR_TIMED_OUT

public static final int PLAYER_ERROR_TIMED_OUT

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

Constant Value: -110 (0xffffff92)

PLAYER_ERROR_UNKNOWN

public static final int PLAYER_ERROR_UNKNOWN

Unspecified player error.

Constant Value: 1 (0x00000001)

PLAYER_ERROR_UNSUPPORTED

public static final int PLAYER_ERROR_UNSUPPORTED

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

Constant Value: -1010 (0xfffffc0e)

SEEK_CLOSEST

public static final int SEEK_CLOSEST

This mode is used with seekTo(long, int) 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:

Constant Value: 3 (0x00000003)

SEEK_CLOSEST_SYNC

public static final int SEEK_CLOSEST_SYNC

This mode is used with seekTo(long, int) 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:

Constant Value: 2 (0x00000002)

SEEK_NEXT_SYNC

public static final int SEEK_NEXT_SYNC

This mode is used with seekTo(long, int) 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:

Constant Value: 1 (0x00000001)

SEEK_PREVIOUS_SYNC

public static final int SEEK_PREVIOUS_SYNC

This mode is used with seekTo(long, int) 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:

Constant Value: 0 (0x00000000)

Public constructors

MediaPlayer

public MediaPlayer (Context context)

Constructor to create a MediaPlayer instance.

Parameters
context Context: A Context that will be used to resolve UriMediaItem.

Public methods

addPlaylistItem

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

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

The implementation may not change the currently playing media item. If index is less than or equal to the current index of the playlist, the current index of the playlist will be increased correspondingly.

The implementation must notify registered callbacks with SessionPlayer.PlayerCallback.onPlaylistChanged(SessionPlayer, List, MediaMetadata) when it's completed.

The implementation must close the ParcelFileDescriptor in the FileMediaItem if the given media item is a FileMediaItem.

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

Parameters
index int: the index of the item you want to add in the playlist

item MediaItem: the media item you want to add

Returns
ListenableFuture<SessionPlayer.PlayerResult>

attachAuxEffect

public ListenableFuture<SessionPlayer.PlayerResult> attachAuxEffect (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(float).

After creating an auxiliary effect (e.g. EnvironmentalReverb), retrieve its ID with AudioEffect.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(MediaItem) and setPlaylist(List, MediaMetadata) methods.

Parameters
effectId int: system wide unique id of the effect to attach

Returns
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

public void close ()

Throws
Exception

getAudioAttributes

public AudioAttributesCompat getAudioAttributes ()

Gets the AudioAttributesCompat that media player has.

Returns
AudioAttributesCompat

getAudioSessionId

public int getAudioSessionId ()

Returns the audio session ID.

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

getBufferedPosition

public long getBufferedPosition ()

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

Returns
long the buffered position in ms, or UNKNOWN_TIME.

getBufferingState

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.

getCurrentMediaItem

public MediaItem getCurrentMediaItem ()

Gets the current media item, which is currently playing or would be played with later play(). This value may be updated when SessionPlayer.PlayerCallback.onCurrentMediaItemChanged(SessionPlayer, MediaItem) or SessionPlayer.PlayerCallback.onPlaylistChanged(SessionPlayer, List, MediaMetadata) is called.

Returns
MediaItem the current media item. Can be null only when media item or playlist hasn't been set.

getCurrentMediaItemIndex

public int getCurrentMediaItemIndex ()

Gets the index of current media item in playlist. This value may be updated when SessionPlayer.PlayerCallback.onCurrentMediaItemChanged(SessionPlayer, MediaItem) or SessionPlayer.PlayerCallback.onPlaylistChanged(SessionPlayer, List, MediaMetadata) 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

public long getCurrentPosition ()

Gets the current playback head position.

Returns
long the current playback position in ms, or UNKNOWN_TIME if unknown.

getDuration

public long getDuration ()

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

Returns
long the duration in ms, or UNKNOWN_TIME.

getMaxPlayerVolume

public float getMaxPlayerVolume ()

Returns
float the maximum volume that can be used in setPlayerVolume(float).

getNextMediaItemIndex

public int getNextMediaItemIndex ()

Gets the next item index in the playlist. The returned value can be outdated after SessionPlayer.PlayerCallback.onCurrentMediaItemChanged(SessionPlayer, MediaItem) or SessionPlayer.PlayerCallback.onPlaylistChanged(SessionPlayer, List, MediaMetadata) 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

public PlaybackParams getPlaybackParams ()

Gets the playback params, containing the current playback rate.

Returns
PlaybackParams the playback params.

getPlaybackSpeed

public 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(float).

Returns
float the actual playback speed

Value is between 0.0 and 3.4028234663852886E38 inclusive.

getPlayerState

public int getPlayerState ()

Gets the current player state.

Returns
int the current player state

getPlayerVolume

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

public List<MediaItem> getPlaylist ()

Gets the playlist. Can be null if the playlist hasn't been set or it's reset by setMediaItem(MediaItem).

Returns
List<MediaItem> playlist, or null

getPlaylistMetadata

public MediaMetadata getPlaylistMetadata ()

Gets the playlist metadata.

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

getPreviousMediaItemIndex

public int getPreviousMediaItemIndex ()

Gets the previous item index in the playlist. The returned value can be outdated after SessionPlayer.PlayerCallback.onCurrentMediaItemChanged(SessionPlayer, MediaItem) or SessionPlayer.PlayerCallback.onPlaylistChanged(SessionPlayer, List, MediaMetadata) 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

public int getRepeatMode ()

Gets the repeat mode.

Returns
int repeat mode

getSelectedTrack

public MediaPlayer.TrackInfo getSelectedTrack (int trackType)

Returns the audio or video track currently selected for playback. The return value is an element in the list returned by getTrackInfo(), and can be used in calls to selectTrack(TrackInfo).

Parameters
trackType int: should be one of MediaPlayer.TrackInfo.MEDIA_TRACK_TYPE_VIDEO or MediaPlayer.TrackInfo.MEDIA_TRACK_TYPE_AUDIO

Returns
MediaPlayer.TrackInfo metadata corresponding to the audio or video 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
IllegalStateException if called after close()

getShuffleMode

public int getShuffleMode ()

Gets the shuffle mode.

Returns
int The shuffle mode

getTimestamp

public 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 MediaTimestamp.getAnchorMediaTimeUs() can be used as current playback position.

Returns
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:

getTrackInfo

public List<MediaPlayer.TrackInfo> getTrackInfo ()

Returns a List of track information.

Returns
List<MediaPlayer.TrackInfo> List of track info. The total number of tracks is the size of the list.

getVideoSize

public VideoSize getVideoSize ()

Returns the size of the video.

Returns
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 MediaPlayer.PlayerCallback can be registered via SessionPlayer.registerPlayerCallback(Executor, SessionPlayer.PlayerCallback) to receive a notification MediaPlayer.PlayerCallback.onVideoSizeChanged(MediaPlayer, MediaItem, VideoSize) when the size is available.

pause

public ListenableFuture<SessionPlayer.PlayerResult> pause ()

Pauses playback.

On success, this transfers the player state to PLAYER_STATE_PAUSED and a SessionPlayer.PlayerResult should 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 should be ignored and a SessionPlayer.PlayerResult should be returned with SessionPlayer.PlayerResult.RESULT_ERROR_INVALID_STATE.

Returns
ListenableFuture<SessionPlayer.PlayerResult>

play

public ListenableFuture<SessionPlayer.PlayerResult> play ()

Starts or resumes playback.

On success, this transfers the player state to PLAYER_STATE_PLAYING and a SessionPlayer.PlayerResult should 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 should be ignored and a SessionPlayer.PlayerResult should be returned with SessionPlayer.PlayerResult.RESULT_ERROR_INVALID_STATE.

Returns
ListenableFuture<SessionPlayer.PlayerResult>

prepare

public ListenableFuture<SessionPlayer.PlayerResult> prepare ()

Prepares the media items for playback.

After setting the media items and the display surface, you need to call this method. During this preparation, the player may allocate resources required to play, such as audio and video decoders.

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

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

registerPlayerCallback

public void registerPlayerCallback (Executor executor, 
                MediaPlayer.PlayerCallback callback)

Register MediaPlayer.PlayerCallback to listen changes.

Parameters
executor Executor: a callback Executor

callback MediaPlayer.PlayerCallback: a PlayerCallback

Throws
IllegalArgumentException if executor or callback is null.

removePlaylistItem

public ListenableFuture<SessionPlayer.PlayerResult> removePlaylistItem (int index)

Removes the media item from the playlist

The implementation may not change the currently playing media item even when it's removed.

The implementation must notify registered callbacks with SessionPlayer.PlayerCallback.onPlaylistChanged(SessionPlayer, List, MediaMetadata) when it's completed.

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

Parameters
index int: the index of the item you want to remove in the playlist

Returns
ListenableFuture<SessionPlayer.PlayerResult>

replacePlaylistItem

public ListenableFuture<SessionPlayer.PlayerResult> replacePlaylistItem (int index, 
                MediaItem item)

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

The implementation must notify registered callbacks with SessionPlayer.PlayerCallback.onPlaylistChanged(SessionPlayer, List, MediaMetadata) when it's completed.

The implementation must close the ParcelFileDescriptor in the FileMediaItem if the given media item is a FileMediaItem.

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

Parameters
index int: the index of the item to replace in the playlist

item MediaItem: the new item

Returns
ListenableFuture<SessionPlayer.PlayerResult>

reset

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

public ListenableFuture<SessionPlayer.PlayerResult> seekTo (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
position long: 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.

mode int: the mode indicating where exactly to seek to.

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

seekTo

public ListenableFuture<SessionPlayer.PlayerResult> seekTo (long position)

Seeks to the specified position. Moves the playback head to the specified position.

On success, a SessionPlayer.PlayerResult should 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 should be returned with SessionPlayer.PlayerResult.RESULT_ERROR_INVALID_STATE.

Parameters
position long: the new playback position in ms. The value should be in the range of start and end positions defined in MediaItem.

Returns
ListenableFuture<SessionPlayer.PlayerResult>

selectTrack

public ListenableFuture<SessionPlayer.PlayerResult> selectTrack (MediaPlayer.TrackInfo trackInfo)

Selects a track.

If the player is in invalid state, SessionPlayer.PlayerResult.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, audio tracks can be selected via this method.

Parameters
trackInfo MediaPlayer.TrackInfo: metadata corresponding to the track to be selected. A trackInfo object can be obtained from getTrackInfo().

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

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

See also:

setAudioAttributes

public ListenableFuture<SessionPlayer.PlayerResult> setAudioAttributes (AudioAttributesCompat attr)

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 should be returned with SessionPlayer.PlayerResult.RESULT_ERROR_INVALID_STATE.

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

Parameters
attr AudioAttributesCompat: non-null AudioAttributes.

Returns
ListenableFuture<SessionPlayer.PlayerResult>

setAudioSessionId

public ListenableFuture<SessionPlayer.PlayerResult> setAudioSessionId (int sessionId)

Sets the audio session ID.

Parameters
sessionId int: 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(MediaItem) and setPlaylist(List, MediaMetadata) methods.

Returns
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

public ListenableFuture<SessionPlayer.PlayerResult> setAuxEffectSendLevel (float level)

Sets the send level of the player to the attached auxiliary effect. See attachAuxEffect(int). 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 < x <= R -> level = 10^(72*(x-R)/20/R)

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

Parameters
level float: send level scalar

Value is between 0.0 and 1.0 inclusive.

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

setMediaItem

public ListenableFuture<SessionPlayer.PlayerResult> setMediaItem (MediaItem item)

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

This can be called multiple times in any states other than PLAYER_STATE_ERROR. This would override previous setMediaItem(MediaItem) or setPlaylist(List, MediaMetadata) calls.

It's recommended to fill MediaMetadata in MediaItem especially for the duration information with the key MediaMetadata.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.

The implementation must notify registered callbacks with SessionPlayer.PlayerCallback.onPlaylistChanged(SessionPlayer, List, MediaMetadata) and SessionPlayer.PlayerCallback.onCurrentMediaItemChanged(SessionPlayer, MediaItem) when it's completed. The current item would be the item given here.

The implementation must close the ParcelFileDescriptor in the FileMediaItem if the given media item is a FileMediaItem.

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

Parameters
item MediaItem: the descriptor of media item you want to play

Returns
ListenableFuture<SessionPlayer.PlayerResult> a ListenableFuture which represents the pending completion of the command.

setPlaybackParams

public ListenableFuture<SessionPlayer.PlayerResult> setPlaybackParams (PlaybackParams params)

Sets playback params using PlaybackParams.

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

Parameters
params PlaybackParams: the playback params.

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

setPlaybackSpeed

public ListenableFuture<SessionPlayer.PlayerResult> setPlaybackSpeed (float playbackSpeed)

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

The supported playback speed range depends on the underlying player implementation, so it is recommended to query the actual speed of the player via getPlaybackSpeed() after the operation completes.

Parameters
playbackSpeed float: The requested playback speed.

Value is between 0.0 and 3.4028234663852886E38 inclusive.

Returns
ListenableFuture<SessionPlayer.PlayerResult> A ListenableFuture representing the pending completion of the command.

setPlayerVolume

public ListenableFuture<SessionPlayer.PlayerResult> setPlayerVolume (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
volume float: a value between 0.0f and getMaxPlayerVolume().

Value is between 0.0 and 1.0 inclusive.

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

setPlaylist

public ListenableFuture<SessionPlayer.PlayerResult> setPlaylist (List<MediaItem> playlist, 
                MediaMetadata metadata)

Sets a list of MediaItem with metadata. Use this or setMediaItem(MediaItem) 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(MediaItem) or setPlaylist(List, MediaMetadata) calls.

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

It's recommended to fill MediaMetadata in each MediaItem especially for the duration information with the key MediaMetadata.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.

The implementation must notify registered callbacks with SessionPlayer.PlayerCallback.onPlaylistChanged(SessionPlayer, List, MediaMetadata) and SessionPlayer.PlayerCallback.onCurrentMediaItemChanged(SessionPlayer, MediaItem) when it's completed. The current media item would be the first item in the playlist.

The implementation must close the ParcelFileDescriptor in the FileMediaItem when a media item in the playlist is a FileMediaItem.

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

Parameters
playlist List: A list of MediaItem objects to set as a play list.

metadata MediaMetadata

Returns
ListenableFuture<SessionPlayer.PlayerResult> a ListenableFuture which represents the pending completion of the command.

setRepeatMode

public ListenableFuture<SessionPlayer.PlayerResult> setRepeatMode (int repeatMode)

Sets the repeat mode.

The implementation must notify registered callbacks with SessionPlayer.PlayerCallback.onRepeatModeChanged(SessionPlayer, int) when it's completed.

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

Parameters
repeatMode int: repeat mode

Returns
ListenableFuture<SessionPlayer.PlayerResult>

setShuffleMode

public ListenableFuture<SessionPlayer.PlayerResult> setShuffleMode (int shuffleMode)

Sets the shuffle mode.

The implementation must notify registered callbacks with SessionPlayer.PlayerCallback.onShuffleModeChanged(SessionPlayer, int) when it's completed.

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

Parameters
shuffleMode int: The shuffle mode

Returns
ListenableFuture<SessionPlayer.PlayerResult>

setSurface

public ListenableFuture<SessionPlayer.PlayerResult> setSurface (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 SurfaceTexture.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
surface Surface: The Surface to be used for the video portion of the media.

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

skipToNextPlaylistItem

public ListenableFuture<SessionPlayer.PlayerResult> skipToNextPlaylistItem ()

Skips to the next item in the playlist.

The implementation must notify registered callbacks with SessionPlayer.PlayerCallback.onCurrentMediaItemChanged(SessionPlayer, MediaItem) when it's completed.

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

Returns
ListenableFuture<SessionPlayer.PlayerResult>

skipToPlaylistItem

public ListenableFuture<SessionPlayer.PlayerResult> skipToPlaylistItem (int index)

Skips to the the media item.

The implementation must notify registered callbacks with SessionPlayer.PlayerCallback.onCurrentMediaItemChanged(SessionPlayer, MediaItem) when it's completed.

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

Parameters
index int: The index of the item you want to play in the playlist

Returns
ListenableFuture<SessionPlayer.PlayerResult>

skipToPreviousPlaylistItem

public ListenableFuture<SessionPlayer.PlayerResult> skipToPreviousPlaylistItem ()

Skips to the previous item in the playlist.

The implementation must notify registered callbacks with SessionPlayer.PlayerCallback.onCurrentMediaItemChanged(SessionPlayer, MediaItem) when it's completed.

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

Returns
ListenableFuture<SessionPlayer.PlayerResult>

unregisterPlayerCallback

public void unregisterPlayerCallback (MediaPlayer.PlayerCallback callback)

Unregister the previously registered MediaPlayer.PlayerCallback.

Parameters
callback MediaPlayer.PlayerCallback: the callback to be removed

Throws
IllegalArgumentException if the callback is null.

updatePlaylistMetadata

public ListenableFuture<SessionPlayer.PlayerResult> updatePlaylistMetadata (MediaMetadata metadata)

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

The implementation must notify registered callbacks with SessionPlayer.PlayerCallback.onPlaylistMetadataChanged(SessionPlayer, MediaMetadata) when it's completed.

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

Parameters
metadata MediaMetadata: metadata of the playlist

Returns
ListenableFuture<SessionPlayer.PlayerResult>