MediaPlayer2

abstract class MediaPlayer2
kotlin.Any
   ↳ androidx.media.MediaPlayer2

MediaPlayer2 class can be used to control playback of audio/video files and streams.

Topics covered here are:

  1. State Diagram
  2. Permissions
  3. Register informational and error callbacks
State Diagram

Playback control of audio/video files and streams is managed as a state machine. The following diagram shows the life cycle and the states of a MediaPlayer2 object driven by the supported playback control operations. The ovals represent the states a MediaPlayer2 object may reside in. The arcs represent the playback control operations that drive the object state transition. There are two types of arcs. The arcs with a single arrow head represent synchronous method calls, while those with a double arrow head represent asynchronous method calls.

From this state diagram, one can see that a MediaPlayer2 object has the following states:

  • When a MediaPlayer2 object is just created using #create() or after #reset() is called, it is in the Idle state; and Once #close() is called, it can no longer be used and there is no way to bring it back to any other state.
    • Calling #setDataSource(DataSourceDesc) and #prepare() transfers a MediaPlayer2 object in the Idle state to the Paused state. It is good programming practice to register a event callback for MediaPlayer2EventCallback#onCallCompleted and look out for #CALL_STATUS_BAD_VALUE and #CALL_STATUS_ERROR_IO that may be caused from #setDataSource.
    • It is also recommended that once a MediaPlayer2 object is no longer being used, call #close() immediately so that resources used by the internal player engine associated with the MediaPlayer2 object can be released immediately. Resource may include singleton resources such as hardware acceleration components and failure to call #close() may cause subsequent instances of MediaPlayer2 objects to fallback to software implementations or fail altogether.
  • In general, some playback control operation may fail due to various reasons, such as unsupported audio/video format, poorly interleaved audio/video, resolution too high, streaming timeout, and the like. Thus, error reporting and recovery is an important concern under these circumstances. Sometimes, due to programming errors, invoking a playback control operation in an invalid state may also occur. Under all these error conditions, the player goes to Error state and invokes a user supplied MediaPlayer2EventCallback#onError} method if an event callback has been registered beforehand via #setMediaPlayer2EventCallback.
  • A MediaPlayer2 object must first enter the Paused state before playback can be started.
  • To start the playback, #play() must be called. Once #play() is processed successfully by the internal media engine, Playing state will be notified with MediaPlayerInterface.PlayerEventCallback#onPlayerStateChanged callback. In addition to the callback, #getMediaPlayer2State() can be called to test whether the MediaPlayer2 object is in the Started state.
  • The playback position can be adjusted with a call to #seekTo.
    • Although the asynchronous #seekTo call returns right away, the actual seek operation may take a while to finish, especially for audio/video being streamed. When the actual seek operation completes, the internal player engine calls a user supplied MediaPlayer2EventCallback.onCallCompleted() with #CALL_COMPLETED_SEEK_TO if an MediaPlayer2EventCallback has been registered beforehand via #setMediaPlayer2EventCallback(Executor, MediaPlayer2EventCallback).
    • Please note that #seekTo(long, int) can also be called in Paused state. When #seekTo(long, int) is called in those states, one video frame will be displayed if the stream has video and the requested position is valid.
    • Furthermore, the actual current playback position can be retrieved with a call to #getCurrentPosition(), which is helpful for applications such as a Music player that need to keep track of the playback progress.
  • When the playback reaches the end of stream, the playback completes. Permissions

    This class requires the android.Manifest.permission#INTERNET permission when used with network-based content.

    Callbacks

    Applications may want to register for informational and error events in order to be informed of some internal state update and possible runtime errors during playback or streaming. Registration for these events is done by properly setting the appropriate listeners (via calls to #setMediaPlayer2EventCallback(Executor, MediaPlayer2EventCallback), #setDrmEventCallback(Executor, DrmEventCallback)). In order to receive the respective callback associated with these listeners, applications are required to create MediaPlayer2 objects on a thread with its own Looper running (main UI thread by default has a Looper running).

Summary

Nested classes
abstract

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

abstract

Encapsulates the DRM properties of the source.

abstract

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

Definitions for the metrics that are reported via the #getMetrics call.

open

Thrown when a DRM method is called before preparing a DRM scheme through prepareDrm().

abstract

Interface definition of a callback to be invoked when the app can do DRM configuration (get/set properties) before the session is opened.

open

Thrown when the device requires DRM provisioning but the provisioning attempt has failed due to a network error (Internet reachability, timeout, etc.

open

Thrown when the device requires DRM provisioning but the provisioning attempt has failed due to the provisioning server denying the request.

abstract

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

Constants
static Int

The player just completed a call #attachAuxEffect.

static Int

The player just completed a call #deselectTrack.

static Int

The player just completed a call #loopCurrent.

static Int

The player just completed a call #pause.

static Int

The player just completed a call #play.

static Int

The player just completed a call #prepare.

static Int

The player just completed a call #seekTo.

static Int

The player just completed a call #selectTrack.

static Int

The player just completed a call #setAudioAttributes.

static Int

The player just completed a call #setAudioSessionId.

static Int

The player just completed a call #setAuxEffectSendLevel.

static Int

The player just completed a call #setDataSource.

static Int

The player just completed a call #setNextDataSource.

static Int

The player just completed a call #setNextDataSources.

static Int

The player just completed a call #setPlaybackParams.

static Int

The player just completed a call #setPlaybackSpeed.

static Int

The player just completed a call #setPlayerVolume.

static Int

The player just completed a call #setSurface.

static Int

The player just completed a call #setSyncParams.

static Int

The player just completed a call #skipToNext.

static Int

Status code represents that the argument is illegal.

static Int

Status code represents a file or network related operation error.

static Int

Status code represents that call is ended with an unknown error.

static Int

Status code represents that the player is not in valid state for the operation.

static Int

Status code represents that call is completed without an error.

static Int

Status code represents that the operation is not allowed.

static Int

MediaPlayer2 has hit some fatal error and cannot continue playback.

static Int

MediaPlayer2 has not been prepared or just has been reset.

static Int

MediaPlayer2 is paused.

static Int

MediaPlayer2 is actively playing back data.

static Int

MediaPlayer2 has been just prepared.

static Int

File or network related operation errors.

static Int

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

static Int

The video is streamed and its container is not valid for progressive playback i.

static Int

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

static Int

Unspecified media player error.

static Int

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

static Int

Informs that audio is not playing.

static Int

The player just rendered the very first audio sample.

static Int

Bad interleaving means that a media has been improperly interleaved or not interleaved at all, e.

static Int

MediaPlayer2 is resuming playback after filling buffers.

static Int

MediaPlayer2 is temporarily pausing playback internally in order to buffer more data.

static Int

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

static Int

A new set of metadata is available.

static Int

The media cannot be seeked (e.

static Int

The player just completed the playback of this data source.

static Int

The player just completed the playback of the full playlist.

static Int

The player just prepared a data source.

static Int

Reading the subtitle track takes too long.

static Int

Unspecified media player info.

static Int

Subtitle track was not supported by the media framework.

static Int

Informs that video is not playing.

static Int

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

static Int

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

static Int

The DRM preparation has failed .

static Int

The device required DRM provisioning but couldn't reach the provisioning server.

static Int

The device required DRM provisioning but the provisioning server denied the request.

static Int

The status codes for DrmEventCallback#onDrmPrepared listener.

static Int

This mode is used with #seekTo(long, int) to move media position to a frame (not necessarily a key frame) associated with a data source that is located closest to or at the given time.

static Int

This mode is used with #seekTo(long, int) to move media position to a sync (or key) frame associated with a data source that is located closest to (in time) or at the given time.

static Int

This mode is used with #seekTo(long, int) to move media position to a sync (or key) frame associated with a data source that is located right after or at the given time.

static Int

This mode is used with #seekTo(long, int) to move media position to a sync (or key) frame associated with a data source that is located right before or at the given time.

static Int

Specifies a video scaling mode.

Public methods
abstract Unit

Sets a single data source as described by a DataSourceDesc which will be played after current data source is finished.

abstract Long

Gets the duration of the file.

abstract DataSourceDesc

Gets the current data source as described by a DataSourceDesc.

abstract Unit
attachAuxEffect(effectId: Int)

Attaches an auxiliary effect to the player.

abstract Unit
selectTrack(index: Int)

Selects a track.

abstract PlaybackParams

Gets the playback params, containing the current playback rate.

open Float

abstract MediaPlayerInterface!

Returns a MediaPlayerInterface implementation which runs based on this MediaPlayer2 instance.

abstract Unit

Sets the playback speed.

abstract Long

Gets the current playback position.

abstract Unit

Starts or resumes playback.

abstract Unit

Sets the callback to be invoked when the media source is ready for playback.

abstract Unit

Sets the data source as described by a DataSourceDesc.

abstract Int
getSelectedTrack(trackType: Int)

Returns the index of the audio, video, or subtitle track currently selected for playback, The return value is an index into the array returned by #getTrackInfo(), and can be used in calls to #selectTrack(int) or #deselectTrack(int).

abstract Unit

Sets playback rate using PlaybackParams.

abstract Unit

Releases the resources held by this MediaPlayer2 object.

abstract ByteArray!
provideDrmKeyResponse(keySetId: ByteArray?, response: ByteArray)

A key response is received from the license server by the app, then it is provided to the DRM engine plugin using provideDrmKeyResponse.

abstract Unit

Sets the callback to be invoked when the media source is ready for playback.

abstract MediaPlayer2.DrmInfo!

Retrieves the DRM Info associated with the current source

abstract Int

Returns the width of the video.

open Float

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

abstract Int

Returns the height of the video.

abstract Unit
setSurface(surface: Surface!)

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

abstract Unit

Clears the DrmEventCallback.

abstract String

Read a DRM engine plugin String property value, given the property name string.

abstract Long

Gets the current buffered media source position received through progressive downloading.

abstract Unit

Deselects a track.

abstract MediaTimestamp?

Gets current playback position as a MediaTimestamp.

abstract Unit

Tries to play next data source if applicable.

abstract Unit

Sets a list of data sources to be played sequentially after current data source is done.

open Unit

Insert a task in the command queue to help the client to identify whether a batch of commands has been finished.

open Unit
seekTo(msec: Long)

Moves the media to specified time position.

abstract Unit
seekTo(msec: Long, mode: Int)

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

abstract Unit

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

abstract Unit

Sets A/V sync mode.

abstract Unit
setDrmPropertyString(propertyName: String, value: String)

Set a DRM engine plugin String property value.

abstract Unit
setAudioSessionId(sessionId: Int)

Sets the audio session ID.

abstract Unit

Restore persisted offline keys into a new session.

abstract Unit

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

abstract Unit

Prepares the DRM for the current source

abstract KeyRequest
getDrmKeyRequest(keySetId: ByteArray?, initData: ByteArray?, mimeType: String?, keyType: Int, optionalParameters: MutableMap<String!, String!>?)

A key request/response exchange occurs between the app and a license server to obtain or release keys used to decrypt encrypted content.

abstract MutableList<MediaPlayer2.TrackInfo!>!

Returns a List of track information.

abstract SyncParams

Gets the A/V sync mode.

abstract Unit

Releases the DRM session

abstract Unit

Resets the MediaPlayer2 to its uninitialized state.

abstract Int

Gets the current MediaPlayer2 state.

abstract Unit

Configures the player to loop on the current data source.

abstract Unit

Prepares the player for playback, asynchronously.

abstract Unit

Pauses playback.

abstract PersistableBundle!

Return Metrics data about the current player.

abstract Unit

Sets the audio attributes for this MediaPlayer2.

open Boolean

Indicates whether reverse playback is supported.

abstract Unit

Discards all pending commands.

abstract AudioAttributesCompat?

Gets the audio attributes for this MediaPlayer2.

abstract Unit

Clears the MediaPlayer2EventCallback.

abstract Int

Returns the audio session ID.

abstract Float

Returns the current volume of this player to this player.

abstract Unit

Register a callback to be invoked for configuration of the DRM object before the session is created.

static MediaPlayer2!

Create a MediaPlayer2 object.

Constants

CALL_COMPLETED_ATTACH_AUX_EFFECT

static val CALL_COMPLETED_ATTACH_AUX_EFFECT: Int

The player just completed a call #attachAuxEffect.

Value: 1

CALL_COMPLETED_DESELECT_TRACK

static val CALL_COMPLETED_DESELECT_TRACK: Int

The player just completed a call #deselectTrack.

Value: 2

CALL_COMPLETED_LOOP_CURRENT

static val CALL_COMPLETED_LOOP_CURRENT: Int

The player just completed a call #loopCurrent.

Value: 3

CALL_COMPLETED_PAUSE

static val CALL_COMPLETED_PAUSE: Int

The player just completed a call #pause.

Value: 4

CALL_COMPLETED_PLAY

static val CALL_COMPLETED_PLAY: Int

The player just completed a call #play.

Value: 5

CALL_COMPLETED_PREPARE

static val CALL_COMPLETED_PREPARE: Int

The player just completed a call #prepare.

Value: 6

CALL_COMPLETED_SEEK_TO

static val CALL_COMPLETED_SEEK_TO: Int

The player just completed a call #seekTo.

Value: 14

CALL_COMPLETED_SELECT_TRACK

static val CALL_COMPLETED_SELECT_TRACK: Int

The player just completed a call #selectTrack.

Value: 15

CALL_COMPLETED_SET_AUDIO_ATTRIBUTES

static val CALL_COMPLETED_SET_AUDIO_ATTRIBUTES: Int

The player just completed a call #setAudioAttributes.

Value: 16

CALL_COMPLETED_SET_AUDIO_SESSION_ID

static val CALL_COMPLETED_SET_AUDIO_SESSION_ID: Int

The player just completed a call #setAudioSessionId.

Value: 17

CALL_COMPLETED_SET_AUX_EFFECT_SEND_LEVEL

static val CALL_COMPLETED_SET_AUX_EFFECT_SEND_LEVEL: Int

The player just completed a call #setAuxEffectSendLevel.

Value: 18

CALL_COMPLETED_SET_DATA_SOURCE

static val CALL_COMPLETED_SET_DATA_SOURCE: Int

The player just completed a call #setDataSource.

Value: 19

CALL_COMPLETED_SET_NEXT_DATA_SOURCE

static val CALL_COMPLETED_SET_NEXT_DATA_SOURCE: Int

The player just completed a call #setNextDataSource.

Value: 22

CALL_COMPLETED_SET_NEXT_DATA_SOURCES

static val CALL_COMPLETED_SET_NEXT_DATA_SOURCES: Int

The player just completed a call #setNextDataSources.

Value: 23

CALL_COMPLETED_SET_PLAYBACK_PARAMS

static val CALL_COMPLETED_SET_PLAYBACK_PARAMS: Int

The player just completed a call #setPlaybackParams.

Value: 24

CALL_COMPLETED_SET_PLAYBACK_SPEED

static val CALL_COMPLETED_SET_PLAYBACK_SPEED: Int

The player just completed a call #setPlaybackSpeed.

Value: 25

CALL_COMPLETED_SET_PLAYER_VOLUME

static val CALL_COMPLETED_SET_PLAYER_VOLUME: Int

The player just completed a call #setPlayerVolume.

Value: 26

CALL_COMPLETED_SET_SURFACE

static val CALL_COMPLETED_SET_SURFACE: Int

The player just completed a call #setSurface.

Value: 27

CALL_COMPLETED_SET_SYNC_PARAMS

static val CALL_COMPLETED_SET_SYNC_PARAMS: Int

The player just completed a call #setSyncParams.

Value: 28

CALL_COMPLETED_SKIP_TO_NEXT

static val CALL_COMPLETED_SKIP_TO_NEXT: Int

The player just completed a call #skipToNext.

Value: 29

CALL_STATUS_BAD_VALUE

static val CALL_STATUS_BAD_VALUE: Int

Status code represents that the argument is illegal.

Value: 2

CALL_STATUS_ERROR_IO

static val CALL_STATUS_ERROR_IO: Int

Status code represents a file or network related operation error.

Value: 4

CALL_STATUS_ERROR_UNKNOWN

static val CALL_STATUS_ERROR_UNKNOWN: Int

Status code represents that call is ended with an unknown error.

Value: -2147483648

CALL_STATUS_INVALID_OPERATION

static val CALL_STATUS_INVALID_OPERATION: Int

Status code represents that the player is not in valid state for the operation.

Value: 1

CALL_STATUS_NO_ERROR

static val CALL_STATUS_NO_ERROR: Int

Status code represents that call is completed without an error.

Value: 0

CALL_STATUS_PERMISSION_DENIED

static val CALL_STATUS_PERMISSION_DENIED: Int

Status code represents that the operation is not allowed.

Value: 3

MEDIAPLAYER2_STATE_ERROR

static val MEDIAPLAYER2_STATE_ERROR: Int

MediaPlayer2 has hit some fatal error and cannot continue playback.

Value: 1005

MEDIAPLAYER2_STATE_IDLE

static val MEDIAPLAYER2_STATE_IDLE: Int

MediaPlayer2 has not been prepared or just has been reset. In this state, MediaPlayer2 doesn't fetch data.

Value: 1001

MEDIAPLAYER2_STATE_PAUSED

static val MEDIAPLAYER2_STATE_PAUSED: Int

MediaPlayer2 is paused. In this state, MediaPlayer2 doesn't actively render data.

Value: 1003

MEDIAPLAYER2_STATE_PLAYING

static val MEDIAPLAYER2_STATE_PLAYING: Int

MediaPlayer2 is actively playing back data.

Value: 1004

MEDIAPLAYER2_STATE_PREPARED

static val MEDIAPLAYER2_STATE_PREPARED: Int

MediaPlayer2 has been just prepared. In this state, MediaPlayer2 just fetches data from media source, but doesn't actively render data.

Value: 1002

MEDIA_ERROR_IO

static val MEDIA_ERROR_IO: Int

File or network related operation errors.

Value: -1004

MEDIA_ERROR_MALFORMED

static val MEDIA_ERROR_MALFORMED: Int

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

Value: -1007

MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK

static val MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK: Int

The video is streamed and its container is not valid for progressive playback i.e the video's index (e.g moov atom) is not at the start of the file.

Value: 200

MEDIA_ERROR_TIMED_OUT

static val MEDIA_ERROR_TIMED_OUT: Int

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

Value: -110

MEDIA_ERROR_UNKNOWN

static val MEDIA_ERROR_UNKNOWN: Int

Unspecified media player error.

Value: 1

MEDIA_ERROR_UNSUPPORTED

static val MEDIA_ERROR_UNSUPPORTED: Int

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

Value: -1010

MEDIA_INFO_AUDIO_NOT_PLAYING

static val MEDIA_INFO_AUDIO_NOT_PLAYING: Int

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

Value: 804

MEDIA_INFO_AUDIO_RENDERING_START

static val MEDIA_INFO_AUDIO_RENDERING_START: Int

The player just rendered the very first audio sample.

Value: 4

MEDIA_INFO_BAD_INTERLEAVING

static val MEDIA_INFO_BAD_INTERLEAVING: 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. Video is playing but a lot of disk seeks may be happening.

Value: 800

MEDIA_INFO_BUFFERING_END

static val MEDIA_INFO_BUFFERING_END: Int

MediaPlayer2 is resuming playback after filling buffers.

Value: 702

MEDIA_INFO_BUFFERING_START

static val MEDIA_INFO_BUFFERING_START: Int

MediaPlayer2 is temporarily pausing playback internally in order to buffer more data.

Value: 701

MEDIA_INFO_BUFFERING_UPDATE

static val MEDIA_INFO_BUFFERING_UPDATE: Int

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

Value: 704

MEDIA_INFO_METADATA_UPDATE

static val MEDIA_INFO_METADATA_UPDATE: Int

A new set of metadata is available.

Value: 802

MEDIA_INFO_NOT_SEEKABLE

static val MEDIA_INFO_NOT_SEEKABLE: Int

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

Value: 801

MEDIA_INFO_PLAYBACK_COMPLETE

static val MEDIA_INFO_PLAYBACK_COMPLETE: Int

The player just completed the playback of this data source.

Value: 5

MEDIA_INFO_PLAYLIST_END

static val MEDIA_INFO_PLAYLIST_END: Int

The player just completed the playback of the full playlist.

Value: 6

MEDIA_INFO_PREPARED

static val MEDIA_INFO_PREPARED: Int

The player just prepared a data source.

Value: 100

MEDIA_INFO_SUBTITLE_TIMED_OUT

static val MEDIA_INFO_SUBTITLE_TIMED_OUT: Int

Reading the subtitle track takes too long.

Value: 902

MEDIA_INFO_UNKNOWN

static val MEDIA_INFO_UNKNOWN: Int

Unspecified media player info.

Value: 1

MEDIA_INFO_UNSUPPORTED_SUBTITLE

static val MEDIA_INFO_UNSUPPORTED_SUBTITLE: Int

Subtitle track was not supported by the media framework.

Value: 901

MEDIA_INFO_VIDEO_NOT_PLAYING

static val MEDIA_INFO_VIDEO_NOT_PLAYING: Int

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

Value: 805

MEDIA_INFO_VIDEO_RENDERING_START

static val MEDIA_INFO_VIDEO_RENDERING_START: Int

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

Value: 3

MEDIA_INFO_VIDEO_TRACK_LAGGING

static val MEDIA_INFO_VIDEO_TRACK_LAGGING: Int

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

Value: 700

PREPARE_DRM_STATUS_PREPARATION_ERROR

static val PREPARE_DRM_STATUS_PREPARATION_ERROR: Int

The DRM preparation has failed .

Value: 3

PREPARE_DRM_STATUS_PROVISIONING_NETWORK_ERROR

static val PREPARE_DRM_STATUS_PROVISIONING_NETWORK_ERROR: Int

The device required DRM provisioning but couldn't reach the provisioning server.

Value: 1

PREPARE_DRM_STATUS_PROVISIONING_SERVER_ERROR

static val PREPARE_DRM_STATUS_PROVISIONING_SERVER_ERROR: Int

The device required DRM provisioning but the provisioning server denied the request.

Value: 2

PREPARE_DRM_STATUS_SUCCESS

static val PREPARE_DRM_STATUS_SUCCESS: Int

The status codes for DrmEventCallback#onDrmPrepared listener.

DRM preparation has succeeded.

Value: 0

SEEK_CLOSEST

static val SEEK_CLOSEST: Int

This mode is used with #seekTo(long, int) to move media position to a frame (not necessarily a key frame) associated with a data source that is located closest to or at the given time.

Value: 3

SEEK_CLOSEST_SYNC

static val SEEK_CLOSEST_SYNC: Int

This mode is used with #seekTo(long, int) to move media position to a sync (or key) frame associated with a data source that is located closest to (in time) or at the given time.

Value: 2

SEEK_NEXT_SYNC

static val SEEK_NEXT_SYNC: Int

This mode is used with #seekTo(long, int) to move media position to a sync (or key) frame associated with a data source that is located right after or at the given time.

Value: 1

SEEK_PREVIOUS_SYNC

static val SEEK_PREVIOUS_SYNC: Int

This mode is used with #seekTo(long, int) to move media position to a sync (or key) frame associated with a data source that is located right before or at the given time.

Value: 0

VIDEO_SCALING_MODE_SCALE_TO_FIT

static val VIDEO_SCALING_MODE_SCALE_TO_FIT: Int

Specifies a video scaling mode. The content is stretched to the surface rendering area. When the surface has the same aspect ratio as the content, the aspect ratio of the content is maintained; otherwise, the aspect ratio of the content is not maintained when video is being rendered. There is no content cropping with this video scaling mode.

Value: 1

Public methods

setNextDataSource

abstract fun setNextDataSource(dsd: DataSourceDesc): Unit

Sets a single data source as described by a DataSourceDesc which will be played after current data source is finished.

Parameters
dsd DataSourceDesc: the descriptor of data source you want to play after current one

getDuration

abstract fun getDuration(): Long

Gets the duration of the file.

Return
Long: the duration in milliseconds, if no duration is available (for example, if streaming live content), -1 is returned.

getCurrentDataSource

abstract fun getCurrentDataSource(): DataSourceDesc

Gets the current data source as described by a DataSourceDesc.

Return
DataSourceDesc: the current DataSourceDesc

attachAuxEffect

abstract fun attachAuxEffect(effectId: Int): Unit

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. android.media.audiofx.EnvironmentalReverb), retrieve its ID with android.media.audiofx.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 after one of the overloaded setDataSource methods.

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

selectTrack

abstract fun selectTrack(index: Int): Unit

Selects a track.

If a MediaPlayer2 is in invalid state, #CALL_STATUS_INVALID_OPERATION will be reported with MediaPlayer2EventCallback#onCallCompleted. If a MediaPlayer2 is in Playing state, the selected track is presented immediately. If a MediaPlayer2 is not in Started 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, Timed Text), 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. However, no timed text track will be selected until this function is called.

Currently, only timed text tracks or audio tracks can be selected via this method.

Parameters
index Int: the index of the track to be selected. The valid range of the index is 0..total number of track - 1. The total number of tracks as well as the type of each individual track can be found by calling #getTrackInfo() method.

getPlaybackParams

abstract fun getPlaybackParams(): PlaybackParams

Gets the playback params, containing the current playback rate.

Return
PlaybackParams: the playback params.

getMaxPlayerVolume

open fun getMaxPlayerVolume(): Float
Return
Float: the maximum volume that can be used in #setPlayerVolume(float).

getMediaPlayerInterface

abstract fun getMediaPlayerInterface(): MediaPlayerInterface!

Returns a MediaPlayerInterface implementation which runs based on this MediaPlayer2 instance.

setPlaybackSpeed

abstract fun setPlaybackSpeed(speed: Float): Unit

Sets the playback speed. A value of 1.0f is the default playback value. A negative value indicates reverse playback, check #isReversePlaybackSupported() before using negative values.
After changing the playback speed, it is recommended to query the actual speed supported by the player, see #getPlaybackSpeed().

Parameters
speed Float: the desired playback speed

getCurrentPosition

abstract fun getCurrentPosition(): Long

Gets the current playback position.

Return
Long: the current position in milliseconds

play

abstract fun play(): Unit

Starts or resumes playback. If playback had previously been paused, playback will continue from where it was paused. If playback had reached end of stream and been paused, or never started before, playback will start at the beginning. If the source had not been prepared, the player will prepare the source and play.

setDrmEventCallback

abstract fun setDrmEventCallback(executor: Executor, eventCallback: MediaPlayer2.DrmEventCallback): Unit

Sets the callback to be invoked when the media source is ready for playback.

Parameters
eventCallback Executor: the callback that will be run
executor Executor: the executor through which the callback should be invoked

setDataSource

abstract fun setDataSource(dsd: DataSourceDesc): Unit

Sets the data source as described by a DataSourceDesc.

Parameters
dsd DataSourceDesc: the descriptor of data source you want to play

getSelectedTrack

abstract fun getSelectedTrack(trackType: Int): Int

Returns the index of the audio, video, or subtitle track currently selected for playback, The return value is an index into the array returned by #getTrackInfo(), and can be used in calls to #selectTrack(int) or #deselectTrack(int).

Parameters
trackType Int: should be one of TrackInfo#MEDIA_TRACK_TYPE_VIDEO, TrackInfo#MEDIA_TRACK_TYPE_AUDIO, or TrackInfo#MEDIA_TRACK_TYPE_SUBTITLE
Return
Int: index of the audio, video, or subtitle track currently selected for playback; a negative integer is returned when there is no selected track for trackType or when trackType is not one of audio, video, or subtitle.
Exceptions
IllegalStateException if called after #close()

setPlaybackParams

abstract fun setPlaybackParams(params: PlaybackParams): Unit

Sets playback rate using PlaybackParams. The object sets its internal PlaybackParams to the input, except that the object remembers previous speed when input speed is zero. This allows the object to resume at previous speed when play() is called. Calling it before the object is prepared does not change the object state. After the object is prepared, calling it with zero speed is equivalent to calling pause(). After the object is prepared, calling it with non-zero speed is equivalent to calling play().

Parameters
params PlaybackParams: the playback params.

close

abstract fun close(): Unit

Releases the resources held by this MediaPlayer2 object. It is considered good practice to call this method when you're done using the MediaPlayer2. In particular, whenever an Activity of an application is paused (its onPause() method is called), or stopped (its onStop() method is called), this method should be invoked to release the MediaPlayer2 object, unless the application has a special need to keep the object around. In addition to unnecessary resources (such as memory and instances of codecs) being held, failure to call this method immediately if a MediaPlayer2 object is no longer needed may also lead to continuous battery consumption for mobile devices, and playback failure for other applications if no multiple instances of the same codec are supported on a device. Even if multiple instances of the same codec are supported, some performance degradation may be expected when unnecessary multiple instances are used at the same time.

provideDrmKeyResponse

abstract fun provideDrmKeyResponse(keySetId: ByteArray?, response: ByteArray): ByteArray!

A key response is received from the license server by the app, then it is provided to the DRM engine plugin using provideDrmKeyResponse. When the response is for an offline key request, a key-set identifier is returned that can be used to later restore the keys to a new session with the method {@ link # restoreDrmKeys}. * When the response is for a streaming or release request, null is returned. * * @param keySetId When the response is for a release request, keySetId identifies * the saved key associated with the release request (i.e., the same keySetId * passed to the earlier {@ link # getDrmKeyRequest} call. It MUST be null when the * response is for either streaming or offline key requests. * * @param response the byte array response from the server * * @throws NoDrmSchemeException if there is no active DRM session * @throws DeniedByServerException if the response indicates that the * server rejected the request

setMediaPlayer2EventCallback

abstract fun setMediaPlayer2EventCallback(executor: Executor, eventCallback: MediaPlayer2.MediaPlayer2EventCallback): Unit

Sets the callback to be invoked when the media source is ready for playback.

Parameters
eventCallback Executor: the callback that will be run
executor Executor: the executor through which the callback should be invoked

getDrmInfo

abstract fun getDrmInfo(): MediaPlayer2.DrmInfo!

Retrieves the DRM Info associated with the current source

Exceptions
IllegalStateException if called before being prepared

getVideoWidth

abstract fun getVideoWidth(): Int

Returns the width of the video.

Return
Int: the width of the video, or 0 if there is no video, no display surface was set, or the width has not been determined yet. The MediaPlayer2EventCallback can be registered via #setMediaPlayer2EventCallback(Executor, MediaPlayer2EventCallback) to provide a notification MediaPlayer2EventCallback.onVideoSizeChanged when the width is available.

getPlaybackSpeed

open fun getPlaybackSpeed(): Float

Returns the actual playback speed to be used by the player when playing. Note that it may differ from the speed set in #setPlaybackSpeed(float).

Return
Float: the actual playback speed

getVideoHeight

abstract fun getVideoHeight(): Int

Returns the height of the video.

Return
Int: the height of the video, or 0 if there is no video, no display surface was set, or the height has not been determined yet. The MediaPlayer2EventCallback can be registered via #setMediaPlayer2EventCallback(Executor, MediaPlayer2EventCallback) to provide a notification MediaPlayer2EventCallback.onVideoSizeChanged when the height is available.

setSurface

abstract fun setSurface(surface: Surface!): Unit

Sets the Surface to be used as the sink for the video portion of the media. Setting a Surface will un-set any Surface or SurfaceHolder that was previously set. 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.

Parameters
surface Surface!: The Surface to be used for the video portion of the media.
Exceptions
IllegalStateException if the internal player engine has not been initialized or has been released.

clearDrmEventCallback

abstract fun clearDrmEventCallback(): Unit

Clears the DrmEventCallback.

getDrmPropertyString

abstract fun getDrmPropertyString(propertyName: String): String

Read a DRM engine plugin String property value, given the property name string.

Parameters
propertyName String: the property name Standard fields names are: MediaDrm#PROPERTY_VENDOR, MediaDrm#PROPERTY_VERSION, MediaDrm#PROPERTY_DESCRIPTION, MediaDrm#PROPERTY_ALGORITHMS

getBufferedPosition

abstract fun getBufferedPosition(): Long

Gets the current buffered media source position 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.

Return
Long: the current buffered media source position in milliseconds

deselectTrack

abstract fun deselectTrack(index: Int): Unit

Deselects a track.

Currently, the track must be a timed text track and no audio or video tracks can be deselected. If the timed text track identified by index has not been selected before, it throws an exception.

Parameters
index Int: the index of the track to be deselected. The valid range of the index is 0..total number of tracks - 1. The total number of tracks as well as the type of each individual track can be found by calling #getTrackInfo() method.

getTimestamp

abstract fun getTimestamp(): MediaTimestamp?

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.

Return
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

skipToNext

abstract fun skipToNext(): Unit

Tries to play next data source if applicable.

setNextDataSources

abstract fun setNextDataSources(dsds: MutableList<DataSourceDesc!>): Unit

Sets a list of data sources to be played sequentially after current data source is done.

Parameters
dsds MutableList<DataSourceDesc!>: the list of data sources you want to play after current one

notifyWhenCommandLabelReached

open fun notifyWhenCommandLabelReached(label: Any): Unit

Insert a task in the command queue to help the client to identify whether a batch of commands has been finished. When this command is processed, a notification MediaPlayer2EventCallback.onCommandLabelReached will be fired with the given label.

Parameters
label Any: An application specific Object used to help to identify the completeness of a batch of commands.

seekTo

open fun seekTo(msec: Long): Unit

Moves the media to specified time position. Same as #seekTo(long, int) with mode = SEEK_PREVIOUS_SYNC.

Parameters
msec Long: the offset in milliseconds from the start to seek to

seekTo

abstract fun seekTo(msec: Long, mode: Int): Unit

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

When seekTo is finished, the user will be notified via MediaPlayer2EventCallback#onInfo with #CALL_COMPLETED_SEEK_TO. 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.

Parameters
msec Long: the offset in milliseconds from the start to seek to. When seeking to the given time position, there is no guarantee that the data source has a frame located at the position. When this happens, a frame nearby will be rendered. If msec is negative, time position zero will be used. If msec is larger than duration, duration will be used.
mode Long: the mode indicating where exactly to seek to.

setPlayerVolume

abstract fun setPlayerVolume(volume: Float): Unit

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.

Parameters
volume Float: a value between 0.0f and #getMaxPlayerVolume().

setSyncParams

abstract fun setSyncParams(params: SyncParams): Unit

Sets A/V sync mode.

Parameters
params SyncParams: the A/V sync params to apply

setDrmPropertyString

abstract fun setDrmPropertyString(propertyName: String, value: String): Unit

Set a DRM engine plugin String property value.

Parameters
propertyName String: the property name
value String: the property value Standard fields names are: MediaDrm#PROPERTY_VENDOR, MediaDrm#PROPERTY_VERSION, MediaDrm#PROPERTY_DESCRIPTION, MediaDrm#PROPERTY_ALGORITHMS

setAudioSessionId

abstract fun setAudioSessionId(sessionId: Int): Unit

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 one of the overloaded setDataSource methods.

restoreDrmKeys

abstract fun restoreDrmKeys(keySetId: ByteArray): Unit

Restore persisted offline keys into a new session. keySetId identifies the keys to load, obtained from a prior call to #provideDrmKeyResponse.

Parameters
keySetId ByteArray: identifies the saved key set to restore

setAuxEffectSendLevel

abstract fun setAuxEffectSendLevel(level: Float): Unit

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)

Parameters
level Float: send level scalar

prepareDrm

abstract fun prepareDrm(uuid: UUID): Unit

Prepares the DRM for the current source

If OnDrmConfigHelper is registered, it will be called during preparation to allow configuration of the DRM properties before opening the DRM session. Note that the callback is called synchronously in the thread that called #prepareDrm. It should be used only for a series of getDrmPropertyString and setDrmPropertyString calls and refrain from any lengthy operation.

If the device has not been provisioned before, this call also provisions the device which involves accessing the provisioning server and can take a variable time to complete depending on the network connectivity. If OnDrmPreparedListener is registered, prepareDrm() runs in non-blocking mode by launching the provisioning in the background and returning. The listener will be called when provisioning and preparation has finished. If a OnDrmPreparedListener is not registered, prepareDrm() waits till provisioning and preparation has finished, i.e., runs in blocking mode.

If OnDrmPreparedListener is registered, it is called to indicate the DRM session being ready. The application should not make any assumption about its call sequence (e.g., before or after prepareDrm returns), or the thread context that will execute the listener (unless the listener is registered with a handler thread).

Parameters
uuid UUID: The UUID of the crypto scheme. If not known beforehand, it can be retrieved from the source through getDrmInfo or registering a onDrmInfoListener.
Exceptions
IllegalStateException if called before being prepared or the DRM was prepared already
UnsupportedSchemeException if the crypto scheme is not supported
ResourceBusyException if required DRM resources are in use
ProvisioningNetworkErrorException if provisioning is required but failed due to a network error
ProvisioningServerErrorException if provisioning is required but failed due to the request denied by the provisioning server

getDrmKeyRequest

abstract fun getDrmKeyRequest(keySetId: ByteArray?, initData: ByteArray?, mimeType: String?, keyType: Int, optionalParameters: MutableMap<String!, String!>?): KeyRequest

A key request/response exchange occurs between the app and a license server to obtain or release keys used to decrypt encrypted content.

getDrmKeyRequest() is used to obtain an opaque key request byte array that is delivered to the license server. The opaque key request byte array is returned in KeyRequest.data. The recommended URL to deliver the key request to is returned in KeyRequest.defaultUrl.

After the app has received the key request response from the server, it should deliver to the response to the DRM engine plugin using the method #provideDrmKeyResponse.

Parameters
keySetId ByteArray?: is the key-set identifier of the offline keys being released when keyType is MediaDrm#KEY_TYPE_RELEASE. It should be set to null for other key requests, when keyType is MediaDrm#KEY_TYPE_STREAMING or MediaDrm#KEY_TYPE_OFFLINE.
initData ByteArray?: is the container-specific initialization data when the keyType is MediaDrm#KEY_TYPE_STREAMING or MediaDrm#KEY_TYPE_OFFLINE. Its meaning is interpreted based on the mime type provided in the mimeType parameter. It could contain, for example, the content ID, key ID or other data obtained from the content metadata that is required in generating the key request. When the keyType is MediaDrm#KEY_TYPE_RELEASE, it should be set to null.
mimeType ByteArray?: identifies the mime type of the content
keyType ByteArray?: specifies the type of the request. The request may be to acquire keys for streaming, MediaDrm#KEY_TYPE_STREAMING, or for offline content MediaDrm#KEY_TYPE_OFFLINE, or to release previously acquired keys (MediaDrm#KEY_TYPE_RELEASE), which are identified by a keySetId.
optionalParameters ByteArray?: are included in the key request message to allow a client application to provide additional message parameters to the server. This may be null if no additional parameters are to be sent.
Exceptions
NoDrmSchemeException if there is no active DRM session

getTrackInfo

abstract fun getTrackInfo(): MutableList<MediaPlayer2.TrackInfo!>!

Returns a List of track information.

Return
MutableList<MediaPlayer2.TrackInfo!>!: List of track info. The total number of tracks is the array length. Must be called again if an external timed text source has been added after addTimedTextSource method is called.

getSyncParams

abstract fun getSyncParams(): SyncParams

Gets the A/V sync mode.

Return
SyncParams: the A/V sync params

releaseDrm

abstract fun releaseDrm(): Unit

Releases the DRM session

The player has to have an active DRM session and be in stopped, or prepared state before this call is made. A reset() call will release the DRM session implicitly.

Exceptions
NoDrmSchemeException if there is no active DRM session to release

reset

abstract fun reset(): Unit

Resets the MediaPlayer2 to its uninitialized state. After calling this method, you will have to initialize it again by setting the data source and calling prepare().

getMediaPlayer2State

abstract fun getMediaPlayer2State(): Int

Gets the current MediaPlayer2 state.

Return
Int: the current MediaPlayer2 state.

loopCurrent

abstract fun loopCurrent(loop: Boolean): Unit

Configures the player to loop on the current data source.

Parameters
loop Boolean: true if the current data source is meant to loop.

prepare

abstract fun prepare(): Unit

Prepares the player for playback, asynchronously. After setting the datasource and the display surface, you need to call prepare().

pause

abstract fun pause(): Unit

Pauses playback. Call play() to resume.

getMetrics

abstract fun getMetrics(): PersistableBundle!

Return Metrics data about the current player.

Return
PersistableBundle!: a PersistableBundle containing the set of attributes and values available for the media being handled by this instance of MediaPlayer2 The attributes are descibed in MetricsConstants. Additional vendor-specific fields may also be present in the return value.

setAudioAttributes

abstract fun setAudioAttributes(attributes: AudioAttributesCompat): Unit

Sets the audio attributes for this MediaPlayer2. See AudioAttributes for how to build and configure an instance of this class. You must call this method before #prepare() in order for the audio attributes to become effective thereafter.

Parameters
attributes AudioAttributesCompat: a non-null set of audio attributes

isReversePlaybackSupported

open fun isReversePlaybackSupported(): Boolean

Indicates whether reverse playback is supported. Reverse playback is indicated by negative playback speeds, see #setPlaybackSpeed(float).

Return
Boolean: true if reverse playback is supported.

clearPendingCommands

abstract fun clearPendingCommands(): Unit

Discards all pending commands.

getAudioAttributes

abstract fun getAudioAttributes(): AudioAttributesCompat?

Gets the audio attributes for this MediaPlayer2.

Return
AudioAttributesCompat?: attributes a set of audio attributes

clearMediaPlayer2EventCallback

abstract fun clearMediaPlayer2EventCallback(): Unit

Clears the MediaPlayer2EventCallback.

getAudioSessionId

abstract fun getAudioSessionId(): Int

Returns the audio session ID.

Return
Int: the audio session ID. {@see #setAudioSessionId(int)} Note that the audio session ID is 0 only if a problem occured when the MediaPlayer2 was contructed.

getPlayerVolume

abstract fun getPlayerVolume(): Float

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

Return
Float: the player volume.

setOnDrmConfigHelper

abstract fun setOnDrmConfigHelper(listener: MediaPlayer2.OnDrmConfigHelper!): Unit

Register a callback to be invoked for configuration of the DRM object before the session is created. The callback will be invoked synchronously during the execution of #prepareDrm(UUID uuid).

Parameters
listener MediaPlayer2.OnDrmConfigHelper!: the callback that will be run

create

static fun create(): MediaPlayer2!

Create a MediaPlayer2 object.

Return
MediaPlayer2!: A MediaPlayer2 object created