Save the date! Android Dev Summit is coming to Sunnyvale, CA on Oct 23-24, 2019.

MediaPlayer2

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

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

Topics covered here are:

  1. Player states
  2. Invalid method calls
  3. Permissions
  4. Callbacks
Player states

The playback control of audio/video files is managed as a state machine.

The MediaPlayer2 object has five states:

  1. PLAYER_STATE_IDLE: MediaPlayer2 is in the Idle state after you create it using create(Context), or after calling reset().

    While in this state, you should call setDataSource(). It is a good programming practice to register an onCallCompleted callback and watch for CALL_STATUS_BAD_VALUE and CALL_STATUS_ERROR_IO, which might be caused by setDataSource.

    Calling prepare() transfers a MediaPlayer2 object to the Prepared state. Note that prepare() is asynchronous. When the preparation completes, If you register a EventCallback#onInfo callback the player executes the callback with MEDIA_INFO_PREPARED before transitioning to the Prepared state.

  2. PLAYER_STATE_PREPARED: A MediaPlayer object must be in the Prepared state before playback can be started for the first time. While in this state, you can set player properties such as audio/sound volume and looping by invoking the corresponding set methods. Calling play() transfers a MediaPlayer2 object to the Playing state.
  3. PLAYER_STATE_PLAYING:

    The player plays the data source while in this state. If you register an EventCallback#onInfo callback the player regularly executes the callback with MEDIA_INFO_BUFFERING_UPDATE. This allows applications to keep track of the buffering status while streaming audio/video.

    When the playback reaches the end of stream, the behavior depends on whether or not you've enabled looping by calling loopCurrent(boolean):

    • If the looping mode was set to false the player will transfer to the Paused state. If you registered an EventCallback#onInfo callback the player calls the callback with MEDIA_INFO_DATA_SOURCE_END before entering the Paused state.
    • If the looping mode was set to true, the MediaPlayer2 object remains in the Playing state and replays its data source from the beginning.
  4. PLAYER_STATE_PAUSED: Audio/video playback pauses while in this state. Call play() to resume playback from the position where it paused.
  5. PLAYER_STATE_ERROR:

    In general, playback might fail due to various reasons such as unsupported audio/video format, poorly interleaved audio/video, resolution too high, streaming timeout, and others. In addition, due to programming errors, a playback control operation might be performed from an invalid state. In these cases the player transitions to the Error state.

    If you register an EventCallback#onError} callback the callback will be performed when entering the state. When programming errors happen, such as calling prepare() and setDataSource(DataSourceDesc2) methods from an invalid state, The callback is called with CALL_STATUS_INVALID_OPERATION . The MediaPlayer2 object enters the Error whether or not a callback exists.

    To recover from an error and reuse a MediaPlayer2 object that is in the Error state, call reset(). The object will return to the Idle state and all state information will be lost.

You should follow these best practices when coding an app that uses MediaPlayer2:

  • Use callbacks to respond to state changes and errors.
  • When a MediaPlayer2 object is no longer being used, call close() as soon as possible to release the resources used by the internal player engine associated with the MediaPlayer2. Failure to call close() may cause subsequent instances of MediaPlayer2 objects to fallback to software implementations or fail altogether. You cannot use MediaPlayer2 after you call close(). There is no way to bring it back to any other state.
  • The 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.
  • 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. If you register an EventCallback#onCallCompleted callback, the callback is called When the seek operation completes with CALL_COMPLETED_SEEK_TO.
  • You can call seekTo(long, int) from the Prepared and Paused states. In these cases, if you are playing a video stream and the requested position is valid one video frame is displayed.
Invalid method calls

The only methods you safely call from the Error state are close(), reset(), notifyWhenCommandLabelReached, clearPendingCommands(), setEventCallback, clearEventCallback() and getState(). Any other methods might throw an exception, return meaningless data, or invoke a EventCallback#onCallCompleted with an error code.

Most methods can be called from any non-Error state. They will either perform their work or silently have no effect. The following table lists the methods that will invoke a EventCallback#onCallCompleted with an error code or throw an exception when they are called from the associated invalid states.

Method Name Invalid States setDataSource {Prepared, Paused, Playing} prepare {Prepared, Paused, Playing} play {Idle} pause {Idle} seekTo {Idle} getCurrentPosition {Idle} getDuration {Idle} getBufferedPosition {Idle} getTrackInfo {Idle} getSelectedTrack {Idle} selectTrack {Idle} deselectTrack {Idle} Permissions

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

Callbacks

Many errors do not result in a transition to the Error state. It is good programming practice to register callback listeners using setEventCallback(Executor, EventCallback) and setDrmEventCallback(Executor, DrmEventCallback)). You can receive a callback at any time and from any state.

If it's important for your app to respond to state changes (for instance, to update the controls on a transport UI), you should register an EventCallback#onCallCompleted and detect state change commands by testing the what parameter for a callback from one of the state transition methods: CALL_COMPLETED_PREPARE, CALL_COMPLETED_PLAY, and CALL_COMPLETED_PAUSE. Then check the status parameter. The value CALL_STATUS_NO_ERROR indicates a successful transition. Any other value will be an error. Call getState() to determine the current state. (You can also register a MediaPlayerConnector.PlayerEventCallback#onPlayerStateChanged callback but this method does not distinguish between the Idle and Prepared states.)

You can also register a MediaPlayerConnector.PlayerEventCallback#onPlayerStateChanged callback. Call getState() from your code to determine the state.

In order for callbacks to work, your app must create MediaPlayer2 objects on a thread that has its own running Looper. This can be done on the main UI thread, which has a Looper.

Summary

Nested classes
abstract

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

abstract

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

abstract

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

abstract

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

abstract

Encapsulates the DRM properties of the source.

open

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

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

Constants
static Int

Specifies a video scaling mode.

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

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 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 frame (not necessarily a key frame) associated with a data source that is located closest to or at the given time.

static Int

MediaPlayer2 has not been prepared or just has been reset.

static Int

MediaPlayer2 has been just prepared.

static Int

MediaPlayer2 is paused.

static Int

MediaPlayer2 is actively playing back data.

static Int

MediaPlayer2 has hit some fatal error and cannot continue playback.

static Int

Unspecified media player error.

static Int

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

static Int

File or network related operation errors.

static Int

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

static Int

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

static Int

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

static Int

Unspecified media player info.

static Int

The player just started the playback of this data source.

static Int

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

static Int

The player just rendered the very first audio sample.

static Int

The player just completed the playback of this data source.

static Int

The player just completed the playback of all the data sources set by setDataSource , setNextDataSource and setNextDataSources.

static Int

The player just completed an iteration of playback loop.

static Int

The player just prepared a data source.

static Int

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

static Int

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

static Int

MediaPlayer2 is resuming playback after filling buffers.

static Int

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

static Int

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

static Int

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

static Int

A new set of metadata is available.

static Int

Informs that audio is not playing.

static Int

Informs that video is not playing.

static Int

Failed to handle timed text track properly.

static Int

Subtitle track was not supported by the media framework.

static Int

Reading the subtitle track takes too long.

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 setPlayerVolume.

static Int

The player just completed a call setSurface.

static Int

The player just completed a call skipToNext.

static Int

Status code represents that call is completed without an 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 the argument is illegal.

static Int

Status code represents that the operation is not allowed.

static Int

Status code represents a file or network related operation error.

static Int

Status code represents that the player skipped the call.

static Int

The status codes for DrmEventCallback#onDrmPrepared listener.

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 DRM preparation has failed.

static Int

The crypto scheme UUID that is not supported by the device.

static Int

The hardware resources are not available, due to being in use.

Public methods
abstract Unit

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

abstract Long

Gets the duration of the file.

abstract DataSourceDesc2

Gets the current data source as described by a DataSourceDesc2.

abstract Unit
attachAuxEffect(effectId: Int)

Attaches an auxiliary effect to the player.

abstract Unit
selectTrack(index: Int)

Selects a track.

abstract PlaybackParams2

Gets the playback params, containing the current playback rate.

open Float

abstract Long

Gets the current playback position.

abstract Unit

Starts or resumes playback.

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

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

abstract Unit

Sets the data source as described by a DataSourceDesc2.

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 PlaybackParams2.

abstract Unit

Releases the resources held by this MediaPlayer2 object.

abstract ByteArray!
provideDrmKeyResponse(@Nullable keySetId: ByteArray?, @NonNull 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 MediaPlayer2.DrmInfo!

Retrieves the DRM Info associated with the current source

abstract Int

Returns the width of the video.

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
setEventCallback(@NonNull executor: Executor, @NonNull eventCallback: MediaPlayer2.EventCallback)

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

abstract Unit

Clears the DrmEventCallback.

abstract String
getDrmPropertyString(@NonNull propertyName: 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 MediaTimestamp2?

Gets current playback position as a MediaTimestamp2.

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
setDrmPropertyString(@NonNull propertyName: String, @NonNull value: String)

Set a DRM engine plugin String property value.

abstract Unit
setAudioSessionId(sessionId: Int)

Sets the audio session ID.

abstract Unit
restoreDrmKeys(@NonNull keySetId: ByteArray)

Restore persisted offline keys into a new session.

abstract Unit

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

abstract Unit
prepareDrm(@NonNull uuid: UUID)

Prepares the DRM for the current source

abstract KeyRequest
getDrmKeyRequest(@Nullable keySetId: ByteArray?, @Nullable initData: ByteArray?, @Nullable mimeType: String?, keyType: Int, @Nullable 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 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 MediaPlayerConnector!

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

abstract PersistableBundle!

Return Metrics data about the current player.

abstract Unit

Sets the audio attributes for this MediaPlayer2.

abstract Unit

Discards all pending commands.

abstract AudioAttributesCompat?

Gets the audio attributes for this MediaPlayer2.

abstract Unit

Clears the EventCallback.

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(@NonNull context: Context)

Create a MediaPlayer2 object.

Constants

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

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: 0x00

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: 0x01

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: 0x02

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: 0x03

PLAYER_STATE_IDLE

static val PLAYER_STATE_IDLE: Int

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

Value: 1001

PLAYER_STATE_PREPARED

static val PLAYER_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

PLAYER_STATE_PAUSED

static val PLAYER_STATE_PAUSED: Int

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

Value: 1003

PLAYER_STATE_PLAYING

static val PLAYER_STATE_PLAYING: Int

MediaPlayer2 is actively playing back data.

Value: 1004

PLAYER_STATE_ERROR

static val PLAYER_STATE_ERROR: Int

MediaPlayer2 has hit some fatal error and cannot continue playback.

Value: 1005

MEDIA_ERROR_UNKNOWN

static val MEDIA_ERROR_UNKNOWN: Int

Unspecified media player error.

Value: 1

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_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_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_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_INFO_UNKNOWN

static val MEDIA_INFO_UNKNOWN: Int

Unspecified media player info.

Value: 1

MEDIA_INFO_DATA_SOURCE_START

static val MEDIA_INFO_DATA_SOURCE_START: Int

The player just started the playback of this data source.

Value: 2

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_AUDIO_RENDERING_START

static val MEDIA_INFO_AUDIO_RENDERING_START: Int

The player just rendered the very first audio sample.

Value: 4

MEDIA_INFO_DATA_SOURCE_END

static val MEDIA_INFO_DATA_SOURCE_END: Int

The player just completed the playback of this data source.

Value: 5

MEDIA_INFO_DATA_SOURCE_LIST_END

static val MEDIA_INFO_DATA_SOURCE_LIST_END: Int

The player just completed the playback of all the data sources set by setDataSource , setNextDataSource and setNextDataSources.

Value: 6

MEDIA_INFO_DATA_SOURCE_REPEAT

static val MEDIA_INFO_DATA_SOURCE_REPEAT: Int

The player just completed an iteration of playback loop. This event is sent only when looping is enabled by loopCurrent.

Value: 7

MEDIA_INFO_PREPARED

static val MEDIA_INFO_PREPARED: Int

The player just prepared a data source.

Value: 100

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

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_END

static val MEDIA_INFO_BUFFERING_END: Int

MediaPlayer2 is resuming playback after filling buffers.

Value: 702

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

Value: 704

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_NOT_SEEKABLE

static val MEDIA_INFO_NOT_SEEKABLE: Int

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

Value: 801

MEDIA_INFO_METADATA_UPDATE

static val MEDIA_INFO_METADATA_UPDATE: Int

A new set of metadata is available.

Value: 802

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_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_TIMED_TEXT_ERROR

static val MEDIA_INFO_TIMED_TEXT_ERROR: Int

Failed to handle timed text track properly.

Value: 900

MEDIA_INFO_UNSUPPORTED_SUBTITLE

static val MEDIA_INFO_UNSUPPORTED_SUBTITLE: Int

Subtitle track was not supported by the media framework.

Value: 901

MEDIA_INFO_SUBTITLE_TIMED_OUT

static val MEDIA_INFO_SUBTITLE_TIMED_OUT: Int

Reading the subtitle track takes too long.

Value: 902

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_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_SKIP_TO_NEXT

static val CALL_COMPLETED_SKIP_TO_NEXT: Int

The player just completed a call skipToNext.

Value: 29

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_ERROR_UNKNOWN

static val CALL_STATUS_ERROR_UNKNOWN: Int

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

Value: Integer.MIN_VALUE

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_BAD_VALUE

static val CALL_STATUS_BAD_VALUE: Int

Status code represents that the argument is illegal.

Value: 2

CALL_STATUS_PERMISSION_DENIED

static val CALL_STATUS_PERMISSION_DENIED: Int

Status code represents that the operation is not allowed.

Value: 3

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_SKIPPED

static val CALL_STATUS_SKIPPED: Int

Status code represents that the player skipped the call. For example, a seekTo request may be skipped if it is followed by another seekTo request.

Value: 5

PREPARE_DRM_STATUS_SUCCESS

static val PREPARE_DRM_STATUS_SUCCESS: Int

The status codes for DrmEventCallback#onDrmPrepared listener.

DRM preparation has succeeded.

Value: 0

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_PREPARATION_ERROR

static val PREPARE_DRM_STATUS_PREPARATION_ERROR: Int

The DRM preparation has failed.

Value: 3

PREPARE_DRM_STATUS_UNSUPPORTED_SCHEME

static val PREPARE_DRM_STATUS_UNSUPPORTED_SCHEME: Int

The crypto scheme UUID that is not supported by the device.

Value: 4

PREPARE_DRM_STATUS_RESOURCE_BUSY

static val PREPARE_DRM_STATUS_RESOURCE_BUSY: Int

The hardware resources are not available, due to being in use.

Value: 5

Public methods

setNextDataSource

abstract fun setNextDataSource(@NonNull dsd: DataSourceDesc2): Unit

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

Parameters
dsd DataSourceDesc2: 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

@NonNull abstract fun getCurrentDataSource(): DataSourceDesc2

Gets the current data source as described by a DataSourceDesc2.

Return
DataSourceDesc2: the current DataSourceDesc2

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 EventCallback#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

@NonNull abstract fun getPlaybackParams(): PlaybackParams2

Gets the playback params, containing the current playback rate.

Return
PlaybackParams2: the playback params.

getMaxPlayerVolume

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

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(@NonNull executor: Executor, @NonNull 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(@NonNull dsd: DataSourceDesc2): Unit

Sets the data source as described by a DataSourceDesc2.

Parameters
dsd DataSourceDesc2: 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(@NonNull params: PlaybackParams2): Unit

Sets playback rate using PlaybackParams2. The object sets its internal PlaybackParams2 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 PlaybackParams2: 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(@Nullable keySetId: ByteArray?, @NonNull 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 restoreDrmKeys. When the response is for a streaming or release request, null is returned.

Parameters
keySetId ByteArray?: 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 getDrmKeyRequest call. It MUST be null when the response is for either streaming or offline key requests.
response ByteArray?: the byte array response from the server
Exceptions
NoDrmSchemeException if there is no active DRM session
DeniedByServerException if the response indicates that the server rejected the request

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 EventCallback can be registered via setEventCallback(Executor, EventCallback) to provide a notification EventCallback#onVideoSizeChanged when the width is available.

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 EventCallback can be registered via setEventCallback(Executor, EventCallback) to provide a notification EventCallback#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.

setEventCallback

abstract fun setEventCallback(@NonNull executor: Executor, @NonNull eventCallback: MediaPlayer2.EventCallback): 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

clearDrmEventCallback

abstract fun clearDrmEventCallback(): Unit

Clears the DrmEventCallback.

getDrmPropertyString

@NonNull abstract fun getDrmPropertyString(@NonNull 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

@Nullable abstract fun getTimestamp(): MediaTimestamp2?

Gets current playback position as a MediaTimestamp2.

The MediaTimestamp2 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 MediaTimestamp2#getAnchorMediaTimeUs can be used as current playback position.

Return
MediaTimestamp2?: a MediaTimestamp2 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(@NonNull dsds: MutableList<DataSourceDesc2!>): Unit

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

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

notifyWhenCommandLabelReached

open fun notifyWhenCommandLabelReached(@NonNull 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 EventCallback#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 EventCallback#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().

setDrmPropertyString

abstract fun setDrmPropertyString(@NonNull propertyName: String, @NonNull 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(@NonNull 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(@NonNull 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. prepareDrm() runs in non-blocking mode by launching the provisioning in the background and returning. DrmEventCallback#onDrmPrepared will be called when provisioning and preparation has finished. The application should check the status code returned with DrmEventCallback#onDrmPrepared to proceed.

Parameters
uuid UUID: The UUID of the crypto scheme. If not known beforehand, it can be retrieved from the source through {#link getDrmInfo} or registering DrmEventCallback#onDrmInfo.

getDrmKeyRequest

@NonNull abstract fun getDrmKeyRequest(@Nullable keySetId: ByteArray?, @Nullable initData: ByteArray?, @Nullable mimeType: String?, keyType: Int, @Nullable 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.

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

getState

abstract fun getState(): 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.

getMediaPlayerConnector

abstract fun getMediaPlayerConnector(): MediaPlayerConnector!

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

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(@NonNull attributes: AudioAttributesCompat): Unit

Sets the audio attributes for this MediaPlayer2. See AudioAttributesCompat 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

clearPendingCommands

abstract fun clearPendingCommands(): Unit

Discards all pending commands.

getAudioAttributes

@Nullable abstract fun getAudioAttributes(): AudioAttributesCompat?

Gets the audio attributes for this MediaPlayer2.

Return
AudioAttributesCompat?: attributes a set of audio attributes

clearEventCallback

abstract fun clearEventCallback(): Unit

Clears the EventCallback.

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(@NonNull context: Context): MediaPlayer2!

Create a MediaPlayer2 object.

Parameters
context Context: The context the player is running in
Return
MediaPlayer2!: A MediaPlayer2 object created