Save the date! Android Dev Summit is coming to Mountain View, CA on November 7-8, 2018.

belongs to Maven artifact androidx.media2:media2:1.0.0-alpha03

MediaPlayer2

public abstract class MediaPlayer2
extends Object

java.lang.Object
   ↳ 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.

MediaPlayer2 State diagram

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 MediaPlayer2.EventCallback.onInfo(MediaPlayer2, DataSourceDesc2, int, int) 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 MediaPlayer2.EventCallback.onInfo(MediaPlayer2, DataSourceDesc2, int, int) 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):

  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 MediaPlayer2.EventCallback.onError(MediaPlayer2, DataSourceDesc2, int, int)} 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(long). Although the asynchronous seekTo(long) call returns right away, the actual seek operation may take a while to finish, especially for audio/video being streamed. If you register an MediaPlayer2.EventCallback.onCallCompleted(MediaPlayer2, DataSourceDesc2, int, int) 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(Object), clearPendingCommands(), setEventCallback(Executor, MediaPlayer2.EventCallback), clearEventCallback() and getState(). Any other methods might throw an exception, return meaningless data, or invoke a MediaPlayer2.EventCallback.onCallCompleted(MediaPlayer2, DataSourceDesc2, int, int) 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 MediaPlayer2.EventCallback.onCallCompleted(MediaPlayer2, DataSourceDesc2, int, int) 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 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 MediaPlayer2.EventCallback.onCallCompleted(MediaPlayer2, DataSourceDesc2, int, int) 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(MediaPlayerConnector, int) callback but this method does not distinguish between the Idle and Prepared states.)

You can also register a MediaPlayerConnector.PlayerEventCallback.onPlayerStateChanged(MediaPlayerConnector, int) 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

class MediaPlayer2.DrmEventCallback

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

class MediaPlayer2.DrmInfo

Encapsulates the DRM properties of the source. 

class MediaPlayer2.EventCallback

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

class MediaPlayer2.MetricsConstants

Definitions for the metrics that are reported via the MediaPlayer2.getMetrics() call. 

class MediaPlayer2.NoDrmSchemeException

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

interface MediaPlayer2.OnDrmConfigHelper

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

class MediaPlayer2.TrackInfo

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

Constants

int CALL_COMPLETED_ATTACH_AUX_EFFECT

The player just completed a call attachAuxEffect(int).

int CALL_COMPLETED_DESELECT_TRACK

The player just completed a call deselectTrack(int).

int CALL_COMPLETED_LOOP_CURRENT

The player just completed a call loopCurrent(boolean).

int CALL_COMPLETED_PAUSE

The player just completed a call pause().

int CALL_COMPLETED_PLAY

The player just completed a call play().

int CALL_COMPLETED_PREPARE

The player just completed a call prepare().

int CALL_COMPLETED_SEEK_TO

The player just completed a call seekTo(long).

int CALL_COMPLETED_SELECT_TRACK

The player just completed a call selectTrack(int).

int CALL_COMPLETED_SET_AUDIO_ATTRIBUTES

The player just completed a call setAudioAttributes(AudioAttributesCompat).

int CALL_COMPLETED_SET_AUDIO_SESSION_ID

The player just completed a call setAudioSessionId(int).

int CALL_COMPLETED_SET_AUX_EFFECT_SEND_LEVEL

The player just completed a call setAuxEffectSendLevel(float).

int CALL_COMPLETED_SET_DATA_SOURCE

The player just completed a call setDataSource(DataSourceDesc2).

int CALL_COMPLETED_SET_NEXT_DATA_SOURCE

The player just completed a call setNextDataSource(DataSourceDesc2).

int CALL_COMPLETED_SET_NEXT_DATA_SOURCES

The player just completed a call setNextDataSources(List).

int CALL_COMPLETED_SET_PLAYBACK_PARAMS

The player just completed a call setPlaybackParams(PlaybackParams2).

int CALL_COMPLETED_SET_PLAYER_VOLUME

The player just completed a call setPlayerVolume(float).

int CALL_COMPLETED_SET_SURFACE

The player just completed a call setSurface(Surface).

int CALL_COMPLETED_SKIP_TO_NEXT

The player just completed a call skipToNext().

int CALL_STATUS_BAD_VALUE

Status code represents that the argument is illegal.

int CALL_STATUS_ERROR_IO

Status code represents a file or network related operation error.

int CALL_STATUS_ERROR_UNKNOWN

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

int CALL_STATUS_INVALID_OPERATION

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

int CALL_STATUS_NO_ERROR

Status code represents that call is completed without an error.

int CALL_STATUS_PERMISSION_DENIED

Status code represents that the operation is not allowed.

int CALL_STATUS_SKIPPED

Status code represents that the player skipped the call.

int MEDIA_ERROR_IO

File or network related operation errors.

int MEDIA_ERROR_MALFORMED

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

int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK

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.

int MEDIA_ERROR_TIMED_OUT

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

int MEDIA_ERROR_UNKNOWN

Unspecified media player error.

int MEDIA_ERROR_UNSUPPORTED

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

int MEDIA_INFO_AUDIO_NOT_PLAYING

Informs that audio is not playing.

int MEDIA_INFO_AUDIO_RENDERING_START

The player just rendered the very first audio sample.

int MEDIA_INFO_BAD_INTERLEAVING

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

int MEDIA_INFO_BUFFERING_END

MediaPlayer2 is resuming playback after filling buffers.

int MEDIA_INFO_BUFFERING_START

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

int MEDIA_INFO_BUFFERING_UPDATE

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

int MEDIA_INFO_DATA_SOURCE_END

The player just completed the playback of this data source.

int MEDIA_INFO_DATA_SOURCE_LIST_END

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

int MEDIA_INFO_DATA_SOURCE_REPEAT

The player just completed an iteration of playback loop.

int MEDIA_INFO_DATA_SOURCE_START

The player just started the playback of this data source.

int MEDIA_INFO_METADATA_UPDATE

A new set of metadata is available.

int MEDIA_INFO_NOT_SEEKABLE

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

int MEDIA_INFO_PREPARED

The player just prepared a data source.

int MEDIA_INFO_SUBTITLE_TIMED_OUT

Reading the subtitle track takes too long.

int MEDIA_INFO_UNKNOWN

Unspecified media player info.

int MEDIA_INFO_UNSUPPORTED_SUBTITLE

Subtitle track was not supported by the media framework.

int MEDIA_INFO_VIDEO_NOT_PLAYING

Informs that video is not playing.

int MEDIA_INFO_VIDEO_RENDERING_START

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

int MEDIA_INFO_VIDEO_TRACK_LAGGING

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

int PLAYER_STATE_ERROR

MediaPlayer2 has hit some fatal error and cannot continue playback.

int PLAYER_STATE_IDLE

MediaPlayer2 has not been prepared or just has been reset.

int PLAYER_STATE_PAUSED

MediaPlayer2 is paused.

int PLAYER_STATE_PLAYING

MediaPlayer2 is actively playing back data.

int PLAYER_STATE_PREPARED

MediaPlayer2 has been just prepared.

int PREPARE_DRM_STATUS_PREPARATION_ERROR

The DRM preparation has failed.

int PREPARE_DRM_STATUS_PROVISIONING_NETWORK_ERROR

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

int PREPARE_DRM_STATUS_PROVISIONING_SERVER_ERROR

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

int PREPARE_DRM_STATUS_RESOURCE_BUSY

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

int PREPARE_DRM_STATUS_SUCCESS

The status codes for MediaPlayer2.DrmEventCallback.onDrmPrepared(MediaPlayer2, DataSourceDesc2, int) listener.

int PREPARE_DRM_STATUS_UNSUPPORTED_SCHEME

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

int SEEK_CLOSEST

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

int SEEK_CLOSEST_SYNC

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

int SEEK_NEXT_SYNC

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

int SEEK_PREVIOUS_SYNC

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

int VIDEO_SCALING_MODE_SCALE_TO_FIT

Specifies a video scaling mode.

Public methods

abstract void attachAuxEffect(int effectId)

Attaches an auxiliary effect to the player.

abstract void clearDrmEventCallback()

Clears the MediaPlayer2.DrmEventCallback.

abstract void clearEventCallback()

Clears the MediaPlayer2.EventCallback.

abstract void clearPendingCommands()

Discards all pending commands.

abstract void close()

Releases the resources held by this MediaPlayer2 object.

static final MediaPlayer2 create(Context context)

Create a MediaPlayer2 object.

abstract void deselectTrack(int index)

Deselects a track.

abstract AudioAttributesCompat getAudioAttributes()

Gets the audio attributes for this MediaPlayer2.

abstract int getAudioSessionId()

Returns the audio session ID.

abstract long getBufferedPosition()

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

abstract DataSourceDesc2 getCurrentDataSource()

Gets the current data source as described by a DataSourceDesc2.

abstract long getCurrentPosition()

Gets the current playback position.

abstract MediaPlayer2.DrmInfo getDrmInfo()

Retrieves the DRM Info associated with the current source

abstract MediaDrm.KeyRequest getDrmKeyRequest(byte[] keySetId, byte[] initData, String mimeType, int keyType, Map<String, String> optionalParameters)

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

abstract String getDrmPropertyString(String propertyName)

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

abstract long getDuration()

Gets the duration of the file.

float getMaxPlayerVolume()
abstract MediaPlayerConnector getMediaPlayerConnector()

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

abstract PersistableBundle getMetrics()

Return Metrics data about the current player.

abstract PlaybackParams2 getPlaybackParams()

Gets the playback params, containing the current playback rate.

abstract float getPlayerVolume()

Returns the current volume of this player to this player.

abstract int getSelectedTrack(int trackType)

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 int getState()

Gets the current MediaPlayer2 state.

abstract MediaTimestamp2 getTimestamp()

Gets current playback position as a MediaTimestamp2.

abstract List<MediaPlayer2.TrackInfo> getTrackInfo()

Returns a List of track information.

abstract int getVideoHeight()

Returns the height of the video.

abstract int getVideoWidth()

Returns the width of the video.

abstract void loopCurrent(boolean loop)

Configures the player to loop on the current data source.

void notifyWhenCommandLabelReached(Object label)

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

abstract void pause()

Pauses playback.

abstract void play()

Starts or resumes playback.

abstract void prepare()

Prepares the player for playback, asynchronously.

abstract void prepareDrm(UUID uuid)

Prepares the DRM for the current source

If MediaPlayer2.OnDrmConfigHelper is registered, it will be called during preparation to allow configuration of the DRM properties before opening the DRM session.

abstract byte[] provideDrmKeyResponse(byte[] keySetId, byte[] response)

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

abstract void releaseDrm()

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.

abstract void reset()

Resets the MediaPlayer2 to its uninitialized state.

abstract void restoreDrmKeys(byte[] keySetId)

Restore persisted offline keys into a new session.

abstract void seekTo(long msec, int mode)

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

void seekTo(long msec)

Moves the media to specified time position.

abstract void selectTrack(int index)

Selects a track.

abstract void setAudioAttributes(AudioAttributesCompat attributes)

Sets the audio attributes for this MediaPlayer2.

abstract void setAudioSessionId(int sessionId)

Sets the audio session ID.

abstract void setAuxEffectSendLevel(float level)

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

abstract void setDataSource(DataSourceDesc2 dsd)

Sets the data source as described by a DataSourceDesc2.

abstract void setDrmEventCallback(Executor executor, MediaPlayer2.DrmEventCallback eventCallback)

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

abstract void setDrmPropertyString(String propertyName, String value)

Set a DRM engine plugin String property value.

abstract void setEventCallback(Executor executor, MediaPlayer2.EventCallback eventCallback)

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

abstract void setNextDataSource(DataSourceDesc2 dsd)

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

abstract void setNextDataSources(List<DataSourceDesc2> dsds)

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

abstract void setOnDrmConfigHelper(MediaPlayer2.OnDrmConfigHelper listener)

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

abstract void setPlaybackParams(PlaybackParams2 params)

Sets playback rate using PlaybackParams2.

abstract void setPlayerVolume(float volume)

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

abstract void setSurface(Surface surface)

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

abstract void skipToNext()

Tries to play next data source if applicable.

Inherited methods

Constants

CALL_COMPLETED_ATTACH_AUX_EFFECT

public static final int CALL_COMPLETED_ATTACH_AUX_EFFECT

The player just completed a call attachAuxEffect(int).

Constant Value: 1 (0x00000001)

CALL_COMPLETED_DESELECT_TRACK

public static final int CALL_COMPLETED_DESELECT_TRACK

The player just completed a call deselectTrack(int).

Constant Value: 2 (0x00000002)

CALL_COMPLETED_LOOP_CURRENT

public static final int CALL_COMPLETED_LOOP_CURRENT

The player just completed a call loopCurrent(boolean).

Constant Value: 3 (0x00000003)

CALL_COMPLETED_PAUSE

public static final int CALL_COMPLETED_PAUSE

The player just completed a call pause().

Constant Value: 4 (0x00000004)

CALL_COMPLETED_PLAY

public static final int CALL_COMPLETED_PLAY

The player just completed a call play().

Constant Value: 5 (0x00000005)

CALL_COMPLETED_PREPARE

public static final int CALL_COMPLETED_PREPARE

The player just completed a call prepare().

Constant Value: 6 (0x00000006)

CALL_COMPLETED_SEEK_TO

public static final int CALL_COMPLETED_SEEK_TO

The player just completed a call seekTo(long).

Constant Value: 14 (0x0000000e)

CALL_COMPLETED_SELECT_TRACK

public static final int CALL_COMPLETED_SELECT_TRACK

The player just completed a call selectTrack(int).

Constant Value: 15 (0x0000000f)

CALL_COMPLETED_SET_AUDIO_ATTRIBUTES

public static final int CALL_COMPLETED_SET_AUDIO_ATTRIBUTES

The player just completed a call setAudioAttributes(AudioAttributesCompat).

Constant Value: 16 (0x00000010)

CALL_COMPLETED_SET_AUDIO_SESSION_ID

public static final int CALL_COMPLETED_SET_AUDIO_SESSION_ID

The player just completed a call setAudioSessionId(int).

Constant Value: 17 (0x00000011)

CALL_COMPLETED_SET_AUX_EFFECT_SEND_LEVEL

public static final int CALL_COMPLETED_SET_AUX_EFFECT_SEND_LEVEL

The player just completed a call setAuxEffectSendLevel(float).

Constant Value: 18 (0x00000012)

CALL_COMPLETED_SET_DATA_SOURCE

public static final int CALL_COMPLETED_SET_DATA_SOURCE

The player just completed a call setDataSource(DataSourceDesc2).

Constant Value: 19 (0x00000013)

CALL_COMPLETED_SET_NEXT_DATA_SOURCE

public static final int CALL_COMPLETED_SET_NEXT_DATA_SOURCE

The player just completed a call setNextDataSource(DataSourceDesc2).

Constant Value: 22 (0x00000016)

CALL_COMPLETED_SET_NEXT_DATA_SOURCES

public static final int CALL_COMPLETED_SET_NEXT_DATA_SOURCES

The player just completed a call setNextDataSources(List).

Constant Value: 23 (0x00000017)

CALL_COMPLETED_SET_PLAYBACK_PARAMS

public static final int CALL_COMPLETED_SET_PLAYBACK_PARAMS

The player just completed a call setPlaybackParams(PlaybackParams2).

Constant Value: 24 (0x00000018)

CALL_COMPLETED_SET_PLAYER_VOLUME

public static final int CALL_COMPLETED_SET_PLAYER_VOLUME

The player just completed a call setPlayerVolume(float).

Constant Value: 26 (0x0000001a)

CALL_COMPLETED_SET_SURFACE

public static final int CALL_COMPLETED_SET_SURFACE

The player just completed a call setSurface(Surface).

Constant Value: 27 (0x0000001b)

CALL_COMPLETED_SKIP_TO_NEXT

public static final int CALL_COMPLETED_SKIP_TO_NEXT

The player just completed a call skipToNext().

Constant Value: 29 (0x0000001d)

CALL_STATUS_BAD_VALUE

public static final int CALL_STATUS_BAD_VALUE

Status code represents that the argument is illegal.

Constant Value: 2 (0x00000002)

CALL_STATUS_ERROR_IO

public static final int CALL_STATUS_ERROR_IO

Status code represents a file or network related operation error.

Constant Value: 4 (0x00000004)

CALL_STATUS_ERROR_UNKNOWN

public static final int CALL_STATUS_ERROR_UNKNOWN

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

Constant Value: -2147483648 (0x80000000)

CALL_STATUS_INVALID_OPERATION

public static final int CALL_STATUS_INVALID_OPERATION

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

Constant Value: 1 (0x00000001)

CALL_STATUS_NO_ERROR

public static final int CALL_STATUS_NO_ERROR

Status code represents that call is completed without an error.

Constant Value: 0 (0x00000000)

CALL_STATUS_PERMISSION_DENIED

public static final int CALL_STATUS_PERMISSION_DENIED

Status code represents that the operation is not allowed.

Constant Value: 3 (0x00000003)

CALL_STATUS_SKIPPED

public static final int CALL_STATUS_SKIPPED

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

Constant Value: 5 (0x00000005)

MEDIA_ERROR_IO

public static final int MEDIA_ERROR_IO

File or network related operation errors.

Constant Value: -1004 (0xfffffc14)

MEDIA_ERROR_MALFORMED

public static final int MEDIA_ERROR_MALFORMED

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

Constant Value: -1007 (0xfffffc11)

MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK

public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK

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.

Constant Value: 200 (0x000000c8)

MEDIA_ERROR_TIMED_OUT

public static final int MEDIA_ERROR_TIMED_OUT

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

Constant Value: -110 (0xffffff92)

MEDIA_ERROR_UNKNOWN

public static final int MEDIA_ERROR_UNKNOWN

Unspecified media player error.

Constant Value: 1 (0x00000001)

MEDIA_ERROR_UNSUPPORTED

public static final int MEDIA_ERROR_UNSUPPORTED

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

Constant Value: -1010 (0xfffffc0e)

MEDIA_INFO_AUDIO_NOT_PLAYING

public static final int MEDIA_INFO_AUDIO_NOT_PLAYING

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

Constant Value: 804 (0x00000324)

MEDIA_INFO_AUDIO_RENDERING_START

public static final int MEDIA_INFO_AUDIO_RENDERING_START

The player just rendered the very first audio sample.

Constant Value: 4 (0x00000004)

MEDIA_INFO_BAD_INTERLEAVING

public static final int MEDIA_INFO_BAD_INTERLEAVING

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

Constant Value: 800 (0x00000320)

MEDIA_INFO_BUFFERING_END

public static final int MEDIA_INFO_BUFFERING_END

MediaPlayer2 is resuming playback after filling buffers.

Constant Value: 702 (0x000002be)

MEDIA_INFO_BUFFERING_START

public static final int MEDIA_INFO_BUFFERING_START

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

Constant Value: 701 (0x000002bd)

MEDIA_INFO_BUFFERING_UPDATE

public static final int MEDIA_INFO_BUFFERING_UPDATE

Update status in buffering a media source received through progressive downloading. The received buffering percentage indicates how much of the content has been buffered or played. For example a buffering update of 80 percent when half the content has already been played indicates that the next 30 percent of the content to play has been buffered. The extra parameter in MediaPlayer2.EventCallback.onInfo(MediaPlayer2, DataSourceDesc2, int, int) is the percentage (0-100) of the content that has been buffered or played thus far.

Constant Value: 704 (0x000002c0)

MEDIA_INFO_DATA_SOURCE_END

public static final int MEDIA_INFO_DATA_SOURCE_END

The player just completed the playback of this data source.

Constant Value: 5 (0x00000005)

MEDIA_INFO_DATA_SOURCE_LIST_END

public static final int MEDIA_INFO_DATA_SOURCE_LIST_END

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

Constant Value: 6 (0x00000006)

MEDIA_INFO_DATA_SOURCE_REPEAT

public static final int MEDIA_INFO_DATA_SOURCE_REPEAT

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

Constant Value: 7 (0x00000007)

MEDIA_INFO_DATA_SOURCE_START

public static final int MEDIA_INFO_DATA_SOURCE_START

The player just started the playback of this data source.

Constant Value: 2 (0x00000002)

MEDIA_INFO_METADATA_UPDATE

public static final int MEDIA_INFO_METADATA_UPDATE

A new set of metadata is available.

Constant Value: 802 (0x00000322)

MEDIA_INFO_NOT_SEEKABLE

public static final int MEDIA_INFO_NOT_SEEKABLE

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

Constant Value: 801 (0x00000321)

MEDIA_INFO_PREPARED

public static final int MEDIA_INFO_PREPARED

The player just prepared a data source.

Constant Value: 100 (0x00000064)

MEDIA_INFO_SUBTITLE_TIMED_OUT

public static final int MEDIA_INFO_SUBTITLE_TIMED_OUT

Reading the subtitle track takes too long.

Constant Value: 902 (0x00000386)

MEDIA_INFO_UNKNOWN

public static final int MEDIA_INFO_UNKNOWN

Unspecified media player info.

Constant Value: 1 (0x00000001)

MEDIA_INFO_UNSUPPORTED_SUBTITLE

public static final int MEDIA_INFO_UNSUPPORTED_SUBTITLE

Subtitle track was not supported by the media framework.

Constant Value: 901 (0x00000385)

MEDIA_INFO_VIDEO_NOT_PLAYING

public static final int MEDIA_INFO_VIDEO_NOT_PLAYING

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

Constant Value: 805 (0x00000325)

MEDIA_INFO_VIDEO_RENDERING_START

public static final int MEDIA_INFO_VIDEO_RENDERING_START

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

Constant Value: 3 (0x00000003)

MEDIA_INFO_VIDEO_TRACK_LAGGING

public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING

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

Constant Value: 700 (0x000002bc)

PLAYER_STATE_ERROR

public static final int PLAYER_STATE_ERROR

MediaPlayer2 has hit some fatal error and cannot continue playback.

Constant Value: 1005 (0x000003ed)

PLAYER_STATE_IDLE

public static final int PLAYER_STATE_IDLE

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

Constant Value: 1001 (0x000003e9)

PLAYER_STATE_PAUSED

public static final int PLAYER_STATE_PAUSED

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

Constant Value: 1003 (0x000003eb)

PLAYER_STATE_PLAYING

public static final int PLAYER_STATE_PLAYING

MediaPlayer2 is actively playing back data.

Constant Value: 1004 (0x000003ec)

PLAYER_STATE_PREPARED

public static final int PLAYER_STATE_PREPARED

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

Constant Value: 1002 (0x000003ea)

PREPARE_DRM_STATUS_PREPARATION_ERROR

public static final int PREPARE_DRM_STATUS_PREPARATION_ERROR

The DRM preparation has failed.

Constant Value: 3 (0x00000003)

PREPARE_DRM_STATUS_PROVISIONING_NETWORK_ERROR

public static final int PREPARE_DRM_STATUS_PROVISIONING_NETWORK_ERROR

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

Constant Value: 1 (0x00000001)

PREPARE_DRM_STATUS_PROVISIONING_SERVER_ERROR

public static final int PREPARE_DRM_STATUS_PROVISIONING_SERVER_ERROR

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

Constant Value: 2 (0x00000002)

PREPARE_DRM_STATUS_RESOURCE_BUSY

public static final int PREPARE_DRM_STATUS_RESOURCE_BUSY

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

Constant Value: 5 (0x00000005)

PREPARE_DRM_STATUS_SUCCESS

public static final int PREPARE_DRM_STATUS_SUCCESS

The status codes for MediaPlayer2.DrmEventCallback.onDrmPrepared(MediaPlayer2, DataSourceDesc2, int) listener.

DRM preparation has succeeded.

Constant Value: 0 (0x00000000)

PREPARE_DRM_STATUS_UNSUPPORTED_SCHEME

public static final int PREPARE_DRM_STATUS_UNSUPPORTED_SCHEME

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

Constant Value: 4 (0x00000004)

SEEK_CLOSEST

public static final int SEEK_CLOSEST

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

See also:

Constant Value: 3 (0x00000003)

SEEK_CLOSEST_SYNC

public static final int SEEK_CLOSEST_SYNC

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

See also:

Constant Value: 2 (0x00000002)

SEEK_NEXT_SYNC

public static final int SEEK_NEXT_SYNC

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

See also:

Constant Value: 1 (0x00000001)

SEEK_PREVIOUS_SYNC

public static final int SEEK_PREVIOUS_SYNC

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

See also:

Constant Value: 0 (0x00000000)

VIDEO_SCALING_MODE_SCALE_TO_FIT

public static final int VIDEO_SCALING_MODE_SCALE_TO_FIT

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.

Constant Value: 1 (0x00000001)

Public methods

attachAuxEffect

public abstract void attachAuxEffect (int effectId)

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

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

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

This method must be called after one of the overloaded setDataSource methods.

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

clearDrmEventCallback

public abstract void clearDrmEventCallback ()

Clears the MediaPlayer2.DrmEventCallback.

clearEventCallback

public abstract void clearEventCallback ()

Clears the MediaPlayer2.EventCallback.

clearPendingCommands

public abstract void clearPendingCommands ()

Discards all pending commands.

close

public abstract void close ()

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.

create

public static final MediaPlayer2 create (Context context)

Create a MediaPlayer2 object.

Parameters
context Context: The context the player is running in

Returns
MediaPlayer2 A MediaPlayer2 object created

deselectTrack

public abstract void deselectTrack (int index)

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.

See also:

getAudioAttributes

public abstract AudioAttributesCompat getAudioAttributes ()

Gets the audio attributes for this MediaPlayer2.

Returns
AudioAttributesCompat attributes a set of audio attributes

getAudioSessionId

public abstract int getAudioSessionId ()

Returns the audio session ID.

Returns
int the audio session ID. Note that the audio session ID is 0 only if a problem occured when the MediaPlayer2 was contructed.

getBufferedPosition

public abstract long getBufferedPosition ()

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.

Returns
long the current buffered media source position in milliseconds

getCurrentDataSource

public abstract DataSourceDesc2 getCurrentDataSource ()

Gets the current data source as described by a DataSourceDesc2.

Returns
DataSourceDesc2 the current DataSourceDesc2

getCurrentPosition

public abstract long getCurrentPosition ()

Gets the current playback position.

Returns
long the current position in milliseconds

getDrmInfo

public abstract MediaPlayer2.DrmInfo getDrmInfo ()

Retrieves the DRM Info associated with the current source

Returns
MediaPlayer2.DrmInfo

Throws
IllegalStateException if called before being prepared

getDrmKeyRequest

public abstract MediaDrm.KeyRequest getDrmKeyRequest (byte[] keySetId, 
                byte[] initData, 
                String mimeType, 
                int keyType, 
                Map<String, String> optionalParameters)

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(byte[], byte[]).

Parameters
keySetId byte: 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 byte: 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 String: identifies the mime type of the content

keyType int: 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 Map: 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.

Returns
MediaDrm.KeyRequest

Throws
MediaPlayer2.NoDrmSchemeException if there is no active DRM session

getDrmPropertyString

public abstract String getDrmPropertyString (String propertyName)

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

Returns
String

Throws
MediaPlayer2.NoDrmSchemeException

getDuration

public abstract long getDuration ()

Gets the duration of the file.

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

getMaxPlayerVolume

public float getMaxPlayerVolume ()

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

getMediaPlayerConnector

public abstract MediaPlayerConnector getMediaPlayerConnector ()

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

Returns
MediaPlayerConnector

getMetrics

public abstract PersistableBundle getMetrics ()

Return Metrics data about the current player.

Returns
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 MediaPlayer2.MetricsConstants. Additional vendor-specific fields may also be present in the return value.

getPlaybackParams

public abstract PlaybackParams2 getPlaybackParams ()

Gets the playback params, containing the current playback rate.

Returns
PlaybackParams2 the playback params.

getPlayerVolume

public abstract float getPlayerVolume ()

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

Returns
float the player volume.

getSelectedTrack

public abstract int getSelectedTrack (int trackType)

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 MediaPlayer2.TrackInfo.MEDIA_TRACK_TYPE_VIDEO, MediaPlayer2.TrackInfo.MEDIA_TRACK_TYPE_AUDIO, or MediaPlayer2.TrackInfo.MEDIA_TRACK_TYPE_SUBTITLE

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

Throws
IllegalStateException if called after close()

getState

public abstract int getState ()

Gets the current MediaPlayer2 state.

Returns
int the current MediaPlayer2 state.

getTimestamp

public abstract MediaTimestamp2 getTimestamp ()

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.

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

getTrackInfo

public abstract List<MediaPlayer2.TrackInfo> getTrackInfo ()

Returns a List of track information.

Returns
List<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.

getVideoHeight

public abstract int getVideoHeight ()

Returns the height of the video.

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

getVideoWidth

public abstract int getVideoWidth ()

Returns the width of the video.

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

loopCurrent

public abstract void loopCurrent (boolean loop)

Configures the player to loop on the current data source.

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

notifyWhenCommandLabelReached

public void notifyWhenCommandLabelReached (Object label)

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 MediaPlayer2.EventCallback.onCommandLabelReached(MediaPlayer2, Object) will be fired with the given label.

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

pause

public abstract void pause ()

Pauses playback. Call play() to resume.

play

public abstract void play ()

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.

prepare

public abstract void prepare ()

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

prepareDrm

public abstract void prepareDrm (UUID uuid)

Prepares the DRM for the current source

If MediaPlayer2.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(UUID). 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. MediaPlayer2.DrmEventCallback.onDrmPrepared(MediaPlayer2, DataSourceDesc2, int) will be called when provisioning and preparation has finished. The application should check the status code returned with MediaPlayer2.DrmEventCallback.onDrmPrepared(MediaPlayer2, DataSourceDesc2, int) 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 MediaPlayer2.DrmEventCallback.onDrmInfo(MediaPlayer2, DataSourceDesc2, MediaPlayer2.DrmInfo).

provideDrmKeyResponse

public abstract byte[] provideDrmKeyResponse (byte[] keySetId, 
                byte[] response)

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(byte[]). When the response is for a streaming or release request, null is returned.

Parameters
keySetId byte: 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(byte[], byte[], String, int, Map) call. It MUST be null when the response is for either streaming or offline key requests.

response byte: the byte array response from the server

Returns
byte[]

Throws
MediaPlayer2.NoDrmSchemeException if there is no active DRM session
DeniedByServerException if the response indicates that the server rejected the request

releaseDrm

public abstract void releaseDrm ()

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.

Throws
MediaPlayer2.NoDrmSchemeException if there is no active DRM session to release

reset

public abstract void reset ()

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

restoreDrmKeys

public abstract void restoreDrmKeys (byte[] keySetId)

Restore persisted offline keys into a new session. keySetId identifies the keys to load, obtained from a prior call to provideDrmKeyResponse(byte[], byte[]).

Parameters
keySetId byte: identifies the saved key set to restore

Throws
MediaPlayer2.NoDrmSchemeException

seekTo

public abstract void seekTo (long msec, 
                int mode)

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

When seekTo is finished, the user will be notified via MediaPlayer2.EventCallback.onInfo(MediaPlayer2, DataSourceDesc2, int, int) 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 int: the mode indicating where exactly to seek to.

seekTo

public void seekTo (long msec)

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

selectTrack

public abstract void selectTrack (int index)

Selects a track.

If a MediaPlayer2 is in invalid state, CALL_STATUS_INVALID_OPERATION will be reported with MediaPlayer2.EventCallback.onCallCompleted(MediaPlayer2, DataSourceDesc2, int, int). 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.

See also:

setAudioAttributes

public abstract void setAudioAttributes (AudioAttributesCompat attributes)

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

setAudioSessionId

public abstract void setAudioSessionId (int sessionId)

Sets the audio session ID.

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

setAuxEffectSendLevel

public abstract void setAuxEffectSendLevel (float level)

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

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

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

Parameters
level float: send level scalar

setDataSource

public abstract void setDataSource (DataSourceDesc2 dsd)

Sets the data source as described by a DataSourceDesc2.

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

setDrmEventCallback

public abstract void setDrmEventCallback (Executor executor, 
                MediaPlayer2.DrmEventCallback eventCallback)

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

Parameters
executor Executor: the executor through which the callback should be invoked

eventCallback MediaPlayer2.DrmEventCallback: the callback that will be run

setDrmPropertyString

public abstract void setDrmPropertyString (String propertyName, 
                String value)

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

Throws
MediaPlayer2.NoDrmSchemeException

setEventCallback

public abstract void setEventCallback (Executor executor, 
                MediaPlayer2.EventCallback eventCallback)

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

Parameters
executor Executor: the executor through which the callback should be invoked

eventCallback MediaPlayer2.EventCallback: the callback that will be run

setNextDataSource

public abstract void setNextDataSource (DataSourceDesc2 dsd)

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

setNextDataSources

public abstract void setNextDataSources (List<DataSourceDesc2> dsds)

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

Parameters
dsds List: the list of data sources you want to play after current one

setOnDrmConfigHelper

public abstract void setOnDrmConfigHelper (MediaPlayer2.OnDrmConfigHelper listener)

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

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

setPlaybackParams

public abstract void setPlaybackParams (PlaybackParams2 params)

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.

setPlayerVolume

public abstract void setPlayerVolume (float volume)

Sets the volume of the audio of the media to play, expressed as a linear multiplier on the audio samples. Note that this volume is specific to the player, and is separate from stream volume used across the platform.
A value of 0.0f indicates muting, a value of 1.0f is the nominal unattenuated and unamplified gain. See getMaxPlayerVolume() for the volume range supported by this player.

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

setSurface

public abstract void setSurface (Surface surface)

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.

Throws
IllegalStateException if the internal player engine has not been initialized or has been released.

skipToNext

public abstract void skipToNext ()

Tries to play next data source if applicable.