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

MediaPlayer2

public class MediaPlayer2
extends Object implements AutoCloseable, AudioRouting

java.lang.Object
   ↳ android.media.MediaPlayer2


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

This API is not generally intended for third party application developers. Use the AndroidX Media2 Library for consistent behavior across all devices.

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 it's created, or after calling reset().

    While in this state, you should call setDataSource. It is a good programming practice to register an EventCallback#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 an EventCallback#onInfo callback, the player executes the callback with MEDIA_INFO_PREPARED and transitions 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 and enters 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(DataSourceDesc) methods from an invalid state, the callback is called with CALL_STATUS_INVALID_OPERATION. The MediaPlayer2 object enters the Error state 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 EventCallback#onCallCompleted callback, the callback is called When the seek operation completes with CALL_COMPLETED_SEEK_TO.
  • You can call seekTo(long) from the Paused state. In this case, 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(), registerEventCallback(Executor, MediaPlayer2.EventCallback), unregisterEventCallback(MediaPlayer2.EventCallback) 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 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 registerEventCallback(Executor, MediaPlayer2.EventCallback). 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.

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

An immutable structure per DataSourceDesc with settings required to initiate a DRM protected playback session. 

class MediaPlayer2.EventCallback

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

class MediaPlayer2.MetricsConstants

 

class MediaPlayer2.NoDrmSchemeException

Thrown when a DRM method is called when there is no active DRM session. 

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_CLEAR_NEXT_DATA_SOURCES

The player just completed a call clearNextDataSources().

int CALL_COMPLETED_DESELECT_TRACK

The player just completed a call deselectTrack(DataSourceDesc, 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(DataSourceDesc, int).

int CALL_COMPLETED_SET_AUDIO_ATTRIBUTES

The player just completed a call setAudioAttributes(AudioAttributes).

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

int CALL_COMPLETED_SET_DISPLAY

The player just completed a call setDisplay(SurfaceHolder).

int CALL_COMPLETED_SET_NEXT_DATA_SOURCE

The player just completed a call setNextDataSource(DataSourceDesc).

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

int CALL_COMPLETED_SET_PLAYER_VOLUME

The player just completed a call setPlayerVolume(float).

int CALL_COMPLETED_SET_SCREEN_ON_WHILE_PLAYING

The player just completed a call setScreenOnWhilePlaying(boolean).

int CALL_COMPLETED_SET_SURFACE

The player just completed a call setSurface(Surface).

int CALL_COMPLETED_SET_SYNC_PARAMS

The player just completed a call setSyncParams(SyncParams).

int CALL_COMPLETED_SET_WAKE_LOCK

The player just completed a call setWakeLock(PowerManager.WakeLock).

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_DRM_SCHEME

Status code represents that DRM operation is called before preparing a DRM scheme through prepareDrm.

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 call has been skipped.

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 data sources set by setDataSource(DataSourceDesc), setNextDataSource(DataSourceDesc) 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 datas 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_KEY_EXCHANGE_ERROR

A status code for DrmEventCallback#onDrmPrepared listener.

int PREPARE_DRM_STATUS_PREPARATION_ERROR

A status code for DrmEventCallback#onDrmPrepared listener.

int PREPARE_DRM_STATUS_PROVISIONING_NETWORK_ERROR

A status code for DrmEventCallback#onDrmPrepared listener.

int PREPARE_DRM_STATUS_PROVISIONING_SERVER_ERROR

A status code for DrmEventCallback#onDrmPrepared listener.

int PREPARE_DRM_STATUS_RESOURCE_BUSY

A status code for DrmEventCallback#onDrmPrepared listener.

int PREPARE_DRM_STATUS_RESTORE_ERROR

A status code for DrmEventCallback#onDrmPrepared listener.

int PREPARE_DRM_STATUS_SUCCESS

A status code for DrmEventCallback#onDrmPrepared listener.

int PREPARE_DRM_STATUS_UNSUPPORTED_SCHEME

A status code for DrmEventCallback#onDrmPrepared listener.

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.

Public constructors

MediaPlayer2(Context context)

Default constructor.

Public methods

void addOnRoutingChangedListener(AudioRouting.OnRoutingChangedListener listener, Handler handler)

Adds an AudioRouting.OnRoutingChangedListener to receive notifications of routing changes on this MediaPlayer2.

Object attachAuxEffect(int effectId)

Attaches an auxiliary effect to the player.

boolean cancelCommand(Object token)

Cancels a pending command.

void clearDrmEventCallback()

Clear the DrmEventCallback.

Object clearNextDataSources()

Removes all data sources pending to be played.

void clearPendingCommands()

Discards all pending commands.

void close()

Releases the resources held by this MediaPlayer2 object.

Object deselectTrack(DataSourceDesc dsd, int index)

Deselect a track.

Object deselectTrack(int index)

Deselect a track of current data source.

AudioAttributes getAudioAttributes()

Gets the audio attributes for this MediaPlayer2.

int getAudioSessionId()

Returns the audio session ID.

long getBufferedPosition(DataSourceDesc dsd)

Gets the buffered media source position of given dsd.

long getBufferedPosition()

Gets the buffered media source position of current data source.

DataSourceDesc getCurrentDataSource()

Gets the current data source as described by a DataSourceDesc.

long getCurrentPosition()

Gets the current playback position.

long getDuration()

Gets the duration of the current data source.

long getDuration(DataSourceDesc dsd)

Gets the duration of the dsd.

float getMaxPlayerVolume()
PersistableBundle getMetrics()

Return Metrics data about the current player.

PlaybackParams getPlaybackParams()

Gets the playback params, containing the current playback rate.

float getPlayerVolume()

Returns the current volume of this player.

AudioDeviceInfo getPreferredDevice()

Returns the selected output specified by setPreferredDevice(AudioDeviceInfo).

AudioDeviceInfo getRoutedDevice()

Returns an AudioDeviceInfo identifying the current routing of this MediaPlayer2 Note: The query is only valid if the MediaPlayer2 is currently playing.

int getSelectedTrack(int trackType)

Returns the index of the audio, video, or subtitle track currently selected for playback.

int getSelectedTrack(DataSourceDesc dsd, int trackType)

Returns the index of the audio, video, or subtitle track currently selected for playback.

int getState()

Gets the current player state.

SyncParams getSyncParams()

Gets the A/V sync mode.

MediaTimestamp getTimestamp()

Get current playback position as a MediaTimestamp.

List<MediaPlayer2.TrackInfo> getTrackInfo(DataSourceDesc dsd)

Returns a List of track information.

List<MediaPlayer2.TrackInfo> getTrackInfo()

Returns a List of track information of current data source.

Size getVideoSize()

Returns the size of the video.

boolean isLooping()

Checks whether the MediaPlayer2 is looping or non-looping.

Object loopCurrent(boolean loop)

Configures the player to loop on the current data source.

Object notifyWhenCommandLabelReached(Object label)

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

Object pause()

Pauses playback.

Object play()

Starts or resumes playback.

Object prepare()

Prepares the player for playback, asynchronously.

void registerEventCallback(Executor executor, MediaPlayer2.EventCallback eventCallback)

Registers the callback to be invoked for various events covered by EventCallback.

void removeOnRoutingChangedListener(AudioRouting.OnRoutingChangedListener listener)

Removes an AudioRouting.OnRoutingChangedListener which has been previously added to receive rerouting notifications.

void reset()

Resets the MediaPlayer2 to its uninitialized state.

Object seekTo(long msec, int mode)

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

Object seekTo(long msec)

Moves the media to specified time position.

Object selectTrack(DataSourceDesc dsd, int index)

Selects a track.

Object selectTrack(int index)

Selects a track of current data source.

Object setAudioAttributes(AudioAttributes attributes)

Sets the audio attributes for this MediaPlayer2.

Object setAudioSessionId(int sessionId)

Sets the audio session ID.

Object setAuxEffectSendLevel(float level)

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

Object setDataSource(DataSourceDesc dsd)

Sets the data source as described by a DataSourceDesc.

Object setDisplay(SurfaceHolder sh)

Sets the SurfaceHolder to use for displaying the video portion of the media.

void setDrmEventCallback(Executor executor, MediaPlayer2.DrmEventCallback eventCallback)

Registers the callback to be invoked for various DRM events.

Object setNextDataSource(DataSourceDesc dsd)

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

Object setNextDataSources(List<DataSourceDesc> dsds)

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

Object setPlaybackParams(PlaybackParams params)

Sets playback rate using PlaybackParams.

Object setPlayerVolume(float volume)

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

boolean setPreferredDevice(AudioDeviceInfo deviceInfo)

Specifies an audio device (via an AudioDeviceInfo object) to route the output from this MediaPlayer2.

Object setScreenOnWhilePlaying(boolean screenOn)

Control whether we should use the attached SurfaceHolder to keep the screen on while video playback is occurring.

Object setSurface(Surface surface)

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

Object setSyncParams(SyncParams params)

Sets A/V sync mode.

Object setWakeLock(PowerManager.WakeLock wakeLock)

Set the low-level power management behavior for this MediaPlayer2.

Object skipToNext()

Tries to play next data source if applicable.

void unregisterEventCallback(MediaPlayer2.EventCallback eventCallback)

Unregisters the EventCallback.

Protected methods

void finalize()

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

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_CLEAR_NEXT_DATA_SOURCES

public static final int CALL_COMPLETED_CLEAR_NEXT_DATA_SOURCES

The player just completed a call clearNextDataSources().

Constant Value: 30 (0x0000001e)

CALL_COMPLETED_DESELECT_TRACK

public static final int CALL_COMPLETED_DESELECT_TRACK

The player just completed a call deselectTrack(DataSourceDesc, 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(DataSourceDesc, 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(AudioAttributes).

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

Constant Value: 19 (0x00000013)

CALL_COMPLETED_SET_DISPLAY

public static final int CALL_COMPLETED_SET_DISPLAY

The player just completed a call setDisplay(SurfaceHolder).

Constant Value: 33 (0x00000021)

CALL_COMPLETED_SET_NEXT_DATA_SOURCE

public static final int CALL_COMPLETED_SET_NEXT_DATA_SOURCE

The player just completed a call setNextDataSource(DataSourceDesc).

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

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_SCREEN_ON_WHILE_PLAYING

public static final int CALL_COMPLETED_SET_SCREEN_ON_WHILE_PLAYING

The player just completed a call setScreenOnWhilePlaying(boolean).

Constant Value: 35 (0x00000023)

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_SET_SYNC_PARAMS

public static final int CALL_COMPLETED_SET_SYNC_PARAMS

The player just completed a call setSyncParams(SyncParams).

Constant Value: 28 (0x0000001c)

CALL_COMPLETED_SET_WAKE_LOCK

public static final int CALL_COMPLETED_SET_WAKE_LOCK

The player just completed a call setWakeLock(PowerManager.WakeLock).

Constant Value: 34 (0x00000022)

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_DRM_SCHEME

public static final int CALL_STATUS_NO_DRM_SCHEME

Status code represents that DRM operation is called before preparing a DRM scheme through prepareDrm.

Constant Value: 6 (0x00000006)

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 call has been skipped. 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. * @apiSince Q

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 EventCallback.onInfo 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 data sources set by setDataSource(DataSourceDesc), setNextDataSource(DataSourceDesc) 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 datas 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 has allocated resources to construct playback pipeline, but it 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_KEY_EXCHANGE_ERROR

public static final int PREPARE_DRM_STATUS_KEY_EXCHANGE_ERROR

A status code for DrmEventCallback#onDrmPrepared listener.

Error during key request/response exchange with license server.

Constant Value: 7 (0x00000007)

PREPARE_DRM_STATUS_PREPARATION_ERROR

public static final int PREPARE_DRM_STATUS_PREPARATION_ERROR

A status code for DrmEventCallback#onDrmPrepared listener.

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

A status code for DrmEventCallback#onDrmPrepared listener.

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

A status code for DrmEventCallback#onDrmPrepared listener.

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

A status code for DrmEventCallback#onDrmPrepared listener.

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

Constant Value: 5 (0x00000005)

PREPARE_DRM_STATUS_RESTORE_ERROR

public static final int PREPARE_DRM_STATUS_RESTORE_ERROR

A status code for DrmEventCallback#onDrmPrepared listener.

Restoring persisted offline keys failed.

Constant Value: 6 (0x00000006)

PREPARE_DRM_STATUS_SUCCESS

public static final int PREPARE_DRM_STATUS_SUCCESS

A status code for DrmEventCallback#onDrmPrepared listener.

DRM preparation has succeeded.

Constant Value: 0 (0x00000000)

PREPARE_DRM_STATUS_UNSUPPORTED_SCHEME

public static final int PREPARE_DRM_STATUS_UNSUPPORTED_SCHEME

A status code for DrmEventCallback#onDrmPrepared listener.

The crypto scheme UUID 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)

Public constructors

MediaPlayer2

public MediaPlayer2 (Context context)

Default constructor.

When done with the MediaPlayer2, you should call close(), to free the resources. If not released, too many MediaPlayer2 instances may result in an exception.

Parameters
context Context

Public methods

addOnRoutingChangedListener

public void addOnRoutingChangedListener (AudioRouting.OnRoutingChangedListener listener, 
                Handler handler)

Adds an AudioRouting.OnRoutingChangedListener to receive notifications of routing changes on this MediaPlayer2.

Parameters
listener AudioRouting.OnRoutingChangedListener: The AudioRouting.OnRoutingChangedListener interface to receive notifications of rerouting events.

handler Handler: Specifies the Handler object for the thread on which to execute the callback. If null, the handler on the main looper will be used.

attachAuxEffect

public Object 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

Returns
Object a token which can be used to cancel the operation later with cancelCommand(Object).

cancelCommand

public boolean cancelCommand (Object token)

Cancels a pending command.

Parameters
token Object: the command to be canceled. This is the returned Object when command is issued. This value must never be null.

Returns
boolean false if the task could not be cancelled; true otherwise.

Throws
IllegalArgumentException if argument token is null.

clearDrmEventCallback

public void clearDrmEventCallback ()

Clear the DrmEventCallback.

clearNextDataSources

public Object clearNextDataSources ()

Removes all data sources pending to be played.

Returns
Object a token which can be used to cancel the operation later with cancelCommand(Object).

clearPendingCommands

public void clearPendingCommands ()

Discards all pending commands.

close

public 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. close() may be safely called after a prior close(). This class implements the Java AutoCloseable interface and may be used with try-with-resources.

deselectTrack

public Object deselectTrack (DataSourceDesc dsd, 
                int index)

Deselect 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
dsd DataSourceDesc: the descriptor of data source of which you want to deselect track This value must never be null.

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.

Returns
Object a token which can be used to cancel the operation later with cancelCommand(Object).

deselectTrack

public Object deselectTrack (int index)

Deselect a track of current data source. Same as deselectTrack(android.media.DataSourceDesc, int) with dsd = getCurrentDataSource().

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.

Returns
Object a token which can be used to cancel the operation later with cancelCommand(Object).

See also:

getAudioAttributes

public AudioAttributes getAudioAttributes ()

Gets the audio attributes for this MediaPlayer2.

Returns
AudioAttributes attributes a set of audio attributes This value will never be null.

getAudioSessionId

public 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 long getBufferedPosition (DataSourceDesc dsd)

Gets the buffered media source position of given dsd. For example a buffering update of 8000 milliseconds when 5000 milliseconds of the content has already been played indicates that the next 3000 milliseconds of the content to play has been buffered.

Parameters
dsd DataSourceDesc: the descriptor of data source of which you want to get buffered position This value must never be null.

Returns
long the current buffered media source position in milliseconds

Throws
NullPointerException if dsd is null

getBufferedPosition

public long getBufferedPosition ()

Gets the buffered media source position of current data source. Same as getBufferedPosition(android.media.DataSourceDesc) with dsd = getCurrentDataSource().

Returns
long the current buffered media source position in milliseconds

Throws
NullPointerException if current data source is null

getCurrentDataSource

public DataSourceDesc getCurrentDataSource ()

Gets the current data source as described by a DataSourceDesc.

Returns
DataSourceDesc the current DataSourceDesc This value may be null.

getCurrentPosition

public long getCurrentPosition ()

Gets the current playback position.

Returns
long the current position in milliseconds

getDuration

public long getDuration ()

Gets the duration of the current data source. Same as getDuration(android.media.DataSourceDesc) with dsd = getCurrentDataSource().

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

Throws
NullPointerException if current data source is null

getDuration

public long getDuration (DataSourceDesc dsd)

Gets the duration of the dsd.

Parameters
dsd DataSourceDesc: the descriptor of data source of which you want to get duration This value must never be null.

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

Throws
NullPointerException if dsd is null

getMaxPlayerVolume

public float getMaxPlayerVolume ()

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

getMetrics

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

getPlaybackParams

public PlaybackParams getPlaybackParams ()

Gets the playback params, containing the current playback rate.

Returns
PlaybackParams the playback params. This value will never be null.

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

getPlayerVolume

public float getPlayerVolume ()

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

Returns
float the player volume.

getPreferredDevice

public AudioDeviceInfo getPreferredDevice ()

Returns the selected output specified by setPreferredDevice(AudioDeviceInfo). Note that this is not guaranteed to correspond to the actual device being used for playback.

Returns
AudioDeviceInfo

getRoutedDevice

public AudioDeviceInfo getRoutedDevice ()

Returns an AudioDeviceInfo identifying the current routing of this MediaPlayer2 Note: The query is only valid if the MediaPlayer2 is currently playing. If the player is not playing, the returned device can be null or correspond to previously selected device when the player was last active.

Returns
AudioDeviceInfo

getSelectedTrack

public 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). Same as getSelectedTrack(android.media.DataSourceDesc, int) with dsd = getCurrentDataSource().

Parameters
trackType int: should be one of TrackInfo#MEDIA_TRACK_TYPE_VIDEO, TrackInfo#MEDIA_TRACK_TYPE_AUDIO, or 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()
NullPointerException if current data source is null

getSelectedTrack

public int getSelectedTrack (DataSourceDesc dsd, 
                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(android.media.DataSourceDesc, int) or deselectTrack(android.media.DataSourceDesc, int).

Parameters
dsd DataSourceDesc: the descriptor of data source of which you want to get selected track This value must never be null.

trackType int: should be one of TrackInfo#MEDIA_TRACK_TYPE_VIDEO, TrackInfo#MEDIA_TRACK_TYPE_AUDIO, or 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()
NullPointerException if dsd is null

getState

public int getState ()

Gets the current player state.

Returns
int the current player state. Value is PLAYER_STATE_IDLE, PLAYER_STATE_PREPARED, PLAYER_STATE_PAUSED, PLAYER_STATE_PLAYING, or PLAYER_STATE_ERROR

getSyncParams

public SyncParams getSyncParams ()

Gets the A/V sync mode.

Returns
SyncParams the A/V sync params This value will never be null.

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

getTimestamp

public MediaTimestamp getTimestamp ()

Get current playback position as a MediaTimestamp.

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

To help users get current playback position, this method always anchors the timestamp to the current System#nanoTime, so MediaTimestamp#getAnchorMediaTimeUs can be used as current playback position.

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

See also:

getTrackInfo

public List<MediaPlayer2.TrackInfo> getTrackInfo (DataSourceDesc dsd)

Returns a List of track information.

Parameters
dsd DataSourceDesc: the descriptor of data source of which you want to get track info This value must never be null.

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.

Throws
IllegalStateException if it is called in an invalid state.
NullPointerException if dsd is null

getTrackInfo

public List<MediaPlayer2.TrackInfo> getTrackInfo ()

Returns a List of track information of current data source. Same as getTrackInfo(android.media.DataSourceDesc) with dsd = getCurrentDataSource().

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.

Throws
IllegalStateException if it is called in an invalid state.
NullPointerException if current data source is null

getVideoSize

public Size getVideoSize ()

Returns the size of the video.

Returns
Size the size of the video. The width and height of size could be 0 if there is no video, no display surface was set, or the size has not been determined yet. The EventCallback can be registered via registerEventCallback(java.util.concurrent.Executor, android.media.MediaPlayer2.EventCallback) to provide a notification EventCallback.onVideoSizeChanged when the size is available.

isLooping

public boolean isLooping ()

Checks whether the MediaPlayer2 is looping or non-looping.

Returns
boolean true if the MediaPlayer2 is currently looping, false otherwise

loopCurrent

public Object 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.

Returns
Object a token which can be used to cancel the operation later with cancelCommand(Object).

notifyWhenCommandLabelReached

public Object 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 EventCallback#onCommandLabelReached 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. This value must never be null.

Returns
Object a token which can be used to cancel the operation later with cancelCommand(Object).

pause

public Object pause ()

Pauses playback. Call play() to resume.

Returns
Object a token which can be used to cancel the operation later with cancelCommand(Object).

play

public Object 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.

Returns
Object a token which can be used to cancel the operation later with cancelCommand(Object).

prepare

public Object prepare ()

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

Returns
Object a token which can be used to cancel the operation later with cancelCommand(Object).

registerEventCallback

public void registerEventCallback (Executor executor, 
                MediaPlayer2.EventCallback eventCallback)

Registers the callback to be invoked for various events covered by EventCallback.

Parameters
executor Executor: the executor through which the callback should be invoked This value must never be null. Callback and listener events are dispatched through this Executor, providing an easy way to control which thread is used. To dispatch events through the main thread of your application, you can use Context#getMainExecutor(). To dispatch events through a shared thread pool, you can use AsyncTask#THREAD_POOL_EXECUTOR.

eventCallback MediaPlayer2.EventCallback: the callback that will be run This value must never be null.

removeOnRoutingChangedListener

public void removeOnRoutingChangedListener (AudioRouting.OnRoutingChangedListener listener)

Removes an AudioRouting.OnRoutingChangedListener which has been previously added to receive rerouting notifications.

Parameters
listener AudioRouting.OnRoutingChangedListener: The previously added AudioRouting.OnRoutingChangedListener interface to remove.

reset

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

seekTo

public Object 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 EventCallback#onCallCompleted 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. Value is SEEK_PREVIOUS_SYNC, SEEK_NEXT_SYNC, SEEK_CLOSEST_SYNC, or SEEK_CLOSEST

Returns
Object a token which can be used to cancel the operation later with cancelCommand(Object).

seekTo

public Object 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

Returns
Object a token which can be used to cancel the operation later with cancelCommand(Object).

selectTrack

public Object selectTrack (DataSourceDesc dsd, 
                int index)

Selects a track.

If a MediaPlayer2 is in invalid state, it throws an IllegalStateException exception. If a MediaPlayer2 is in Started 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. In addition, the support for selecting an audio track at runtime is pretty limited in that an audio track can only be selected in the Prepared state.

Parameters
dsd DataSourceDesc: the descriptor of data source of which you want to select track This value must never be null.

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(android.media.DataSourceDesc) method.

Returns
Object a token which can be used to cancel the operation later with cancelCommand(Object).

selectTrack

public Object selectTrack (int index)

Selects a track of current data source. Same as selectTrack(android.media.DataSourceDesc, int) with dsd = getCurrentDataSource().

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.

Returns
Object a token which can be used to cancel the operation later with cancelCommand(Object).

See also:

setAudioAttributes

public Object setAudioAttributes (AudioAttributes attributes)

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

Parameters
attributes AudioAttributes: a non-null set of audio attributes This value must never be null.

Returns
Object a token which can be used to cancel the operation later with cancelCommand(Object).

setAudioSessionId

public Object 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 when player is in PLAYER_STATE_IDLE or PLAYER_STATE_PREPARED state in order to have sessionId take effect.

Returns
Object a token which can be used to cancel the operation later with cancelCommand(Object).

setAuxEffectSendLevel

public Object 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

Returns
Object a token which can be used to cancel the operation later with cancelCommand(Object).

setDataSource

public Object setDataSource (DataSourceDesc dsd)

Sets the data source as described by a DataSourceDesc. When the data source is of FileDataSourceDesc type, the ParcelFileDescriptor in the FileDataSourceDesc will be closed by the player.

Parameters
dsd DataSourceDesc: the descriptor of data source you want to play This value must never be null.

Returns
Object a token which can be used to cancel the operation later with cancelCommand(Object).

setDisplay

public Object setDisplay (SurfaceHolder sh)

Sets the SurfaceHolder to use for displaying the video portion of the media. Either a surface holder or surface must be set if a display or video sink is needed. Not calling this method or setSurface(android.view.Surface) when playing back a video will result in only the audio track being played. A null surface holder or surface will result in only the audio track being played.

Parameters
sh SurfaceHolder: the SurfaceHolder to use for video display

Returns
Object a token which can be used to cancel the operation later with cancelCommand(Object).

setDrmEventCallback

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

Registers the callback to be invoked for various DRM events.

Parameters
executor Executor: the executor through which the callback should be invoked This value must never be null. Callback and listener events are dispatched through this Executor, providing an easy way to control which thread is used. To dispatch events through the main thread of your application, you can use Context#getMainExecutor(). To dispatch events through a shared thread pool, you can use AsyncTask#THREAD_POOL_EXECUTOR.

eventCallback MediaPlayer2.DrmEventCallback: the callback that will be run This value must never be null.

setNextDataSource

public Object setNextDataSource (DataSourceDesc dsd)

Sets a single data source as described by a DataSourceDesc which will be played after current data source is finished. When the data source is of FileDataSourceDesc type, the ParcelFileDescriptor in the FileDataSourceDesc will be closed by the player.

Parameters
dsd DataSourceDesc: the descriptor of data source you want to play after current one This value must never be null.

Returns
Object a token which can be used to cancel the operation later with cancelCommand(Object).

setNextDataSources

public Object setNextDataSources (List<DataSourceDesc> dsds)

Sets a list of data sources to be played sequentially after current data source is done. When the data source is of FileDataSourceDesc type, the ParcelFileDescriptor in the FileDataSourceDesc will be closed by the player.

Parameters
dsds List: the list of data sources you want to play after current one This value must never be null.

Returns
Object a token which can be used to cancel the operation later with cancelCommand(Object).

setPlaybackParams

public Object setPlaybackParams (PlaybackParams params)

Sets playback rate using PlaybackParams. The object sets its internal PlaybackParams to the input. This allows the object to resume at previous speed when play() is called. Speed of zero is not allowed. Calling it does not change the object state.

Parameters
params PlaybackParams: the playback params. This value must never be null.

Returns
Object a token which can be used to cancel the operation later with cancelCommand(Object).

setPlayerVolume

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

Returns
Object a token which can be used to cancel the operation later with cancelCommand(Object).

setPreferredDevice

public boolean setPreferredDevice (AudioDeviceInfo deviceInfo)

Specifies an audio device (via an AudioDeviceInfo object) to route the output from this MediaPlayer2.

Parameters
deviceInfo AudioDeviceInfo: The AudioDeviceInfo specifying the audio sink or source. If deviceInfo is null, default routing is restored.

Returns
boolean true if succesful, false if the specified AudioDeviceInfo is non-null and does not correspond to a valid audio device.

setScreenOnWhilePlaying

public Object setScreenOnWhilePlaying (boolean screenOn)

Control whether we should use the attached SurfaceHolder to keep the screen on while video playback is occurring. This is the preferred method over setWakeLock(PowerManager.WakeLock) where possible, since it doesn't require that the application have permission for low-level wake lock access.

Parameters
screenOn boolean: Supply true to keep the screen on, false to allow it to turn off.

Returns
Object a token which can be used to cancel the operation later with cancelCommand(Object).

setSurface

public Object 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.

Returns
Object a token which can be used to cancel the operation later with cancelCommand(Object).

setSyncParams

public Object setSyncParams (SyncParams params)

Sets A/V sync mode.

Parameters
params SyncParams: the A/V sync params to apply This value must never be null.

Returns
Object a token which can be used to cancel the operation later with cancelCommand(Object).

setWakeLock

public Object setWakeLock (PowerManager.WakeLock wakeLock)

Set the low-level power management behavior for this MediaPlayer2. This can be used when the MediaPlayer2 is not playing through a SurfaceHolder set with setDisplay(android.view.SurfaceHolder) and thus can use the high-level setScreenOnWhilePlaying(boolean) feature.

This function has the MediaPlayer2 access the low-level power manager service to control the device's power usage while playing is occurring. The parameter is a PowerManager.WakeLock. Use of this method requires Manifest.permission.WAKE_LOCK permission. By default, no attempt is made to keep the device awake during playback.

Parameters
wakeLock PowerManager.WakeLock: the power wake lock used during playback. This value must never be null.

Returns
Object a token which can be used to cancel the operation later with cancelCommand(Object).

See also:

skipToNext

public Object skipToNext ()

Tries to play next data source if applicable.

Returns
Object a token which can be used to cancel the operation later with cancelCommand(Object).

unregisterEventCallback

public void unregisterEventCallback (MediaPlayer2.EventCallback eventCallback)

Unregisters the EventCallback.

Parameters
eventCallback MediaPlayer2.EventCallback: the callback to be unregistered

Protected methods

finalize

protected void finalize ()

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.

The general contract of finalize is that it is invoked if and when the Java™ virtual machine has determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, except as a result of an action taken by the finalization of some other object or class which is ready to be finalized. The finalize method may take any action, including making this object available again to other threads; the usual purpose of finalize, however, is to perform cleanup actions before the object is irrevocably discarded. For example, the finalize method for an object that represents an input/output connection might perform explicit I/O transactions to break the connection before the object is permanently discarded.

The finalize method of class Object performs no special action; it simply returns normally. Subclasses of Object may override this definition.

The Java programming language does not guarantee which thread will invoke the finalize method for any given object. It is guaranteed, however, that the thread that invokes finalize will not be holding any user-visible synchronization locks when finalize is invoked. If an uncaught exception is thrown by the finalize method, the exception is ignored and finalization of that object terminates.

After the finalize method has been invoked for an object, no further action is taken until the Java virtual machine has again determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, including possible actions by other objects or classes which are ready to be finalized, at which point the object may be discarded.

The finalize method is never invoked more than once by a Java virtual machine for any given object.

Any exception thrown by the finalize method causes the finalization of this object to be halted, but is otherwise ignored.

Throws
Throwable