MediaController
@DoNotMock
public class MediaController implements Player
MediaBrowser |
Browses media content offered by a |
A controller that interacts with a MediaSession, a MediaSessionService hosting a MediaSession, or a MediaLibraryService hosting a MediaLibraryService.MediaLibrarySession. The MediaSession typically resides in a remote process like another app but may be in the same process as this controller. It implements Player and the player commands are sent to the underlying Player of the connected MediaSession. It also has session-specific commands that can be handled by MediaSession.Callback.
Topics covered here:
- Controller Lifecycle
- Threading Model
- Package Visibility Filter
- Backward Compatibility with platform and legacy media sessions
Controller Lifecycle
When a controller is created with the SessionToken for a MediaSession (i.e. session token type is TYPE_SESSION), the controller will connect to the specific session.
When a controller is created with the SessionToken for a MediaSessionService (i.e. session token type is TYPE_SESSION_SERVICE or TYPE_LIBRARY_SERVICE), the controller binds to the service for connecting to a MediaSession in it. MediaSessionService will provide a session to connect.
When you're done, use releaseFuture or release to clean up resources. This also helps the session service to be destroyed when there's no controller associated with it. Releasing the controller will still deliver all pending commands sent to the session and only unbind from the session service once these commands have been handled, or after a timeout of RELEASE_UNBIND_TIMEOUT_MS.
Threading Model
Methods of this class should be called from the application thread associated with the application looper. Otherwise, IllegalStateException will be thrown. Also, the methods of Player.Listener and Listener will be called from the application thread.
Package Visibility Filter
The app targeting API level 30 or higher must include a <queries> element in their manifest to connect to a service component of another app like MediaSessionService, MediaLibraryService, or androidx.media.MediaBrowserServiceCompat). See the following example and this guide for more information.
<!-- As intent actions --> <intent> <action android:name="androidx.media3.session.MediaSessionService" /> </intent> <intent> <action android:name="androidx.media3.session.MediaLibraryService" /> </intent> <intent> <action android:name="android.media.browse.MediaBrowserService" /> </intent> <!-- Or, as a package name --> <package android:name="package_name_of_the_other_app" />
Backward Compatibility with platform and legacy media sessions
In addition to MediaSession, the controller also supports connecting to a platform or legacy media session - android.media.session.MediaSession and
android.support.v4.media.session.MediaSessionCompat.
To request legacy sessions to play media, use one of the setMediaItem methods and set either mediaId, mediaUri or searchQuery. Once the controller is prepared, the controller triggers one of the following methods on
android.support.v4.media.session.MediaSessionCompat.Callback depending on the provided information and the value of getPlayWhenReady:
onPrepareFromUrionPlayFromUrionPrepareFromMediaIdonPlayFromMediaIdonPrepareFromSearchonPlayFromSearch
addMediaItem or removeMediaItem, trigger the MediaSessionCompat.Callback.onAddQueueItem and
MediaSessionCompat.Callback.onRemoveQueueItem callbacks. Check getAvailableCommands to see if playlist modifications are supported by the legacy session.
Summary
Nested types |
|---|
public final class MediaController.BuilderA builder for |
public interface MediaController.ListenerA listener for events and incoming commands from |
@UnstableApiA listener to receive progress updates of a custom command when a custom command is sent and a non-null |
Constants |
|
|---|---|
static final long |
|
static final String |
@UnstableApiKey to mark the connection hints of the media notification controller. |
static final long |
@UnstableApiThe timeout for handling pending commands after calling |
Public methods |
|
|---|---|
final void |
addListener(Player.Listener listener)Registers a listener to receive all events from the player. |
final void |
addMediaItem(MediaItem mediaItem)Adds a media item to the end of the playlist. |
final void |
addMediaItem(int index, MediaItem mediaItem)Adds a media item at the given index of the playlist. |
final void |
addMediaItems(List<MediaItem> mediaItems)Adds a list of media items to the end of the playlist. |
final void |
addMediaItems(int index, List<MediaItem> mediaItems)Adds a list of media items at the given index of the playlist. |
final boolean |
Returns whether the player can be used to advertise a media session. |
final void |
Clears the playlist. |
final void |
Clears any |
final void |
clearVideoSurface(@Nullable Surface surface)Clears the |
final void |
clearVideoSurfaceHolder(@Nullable SurfaceHolder surfaceHolder)Clears the |
final void |
clearVideoSurfaceView(@Nullable SurfaceView surfaceView)Clears the |
final void |
clearVideoTextureView(@Nullable TextureView textureView)Clears the |
final void |
This method is deprecated. Use |
final void |
decreaseDeviceVolume(@C.VolumeFlags int flags)Decreases the volume of the device. |
final Looper |
Returns the |
final AudioAttributes |
Returns the attributes for audio playback. |
final int |
Returns the audio session identifier, or |
final Player.Commands |
Returns the player's currently available |
final SessionCommands |
Returns the current available session commands from |
final @IntRange(from = 0, to = 100) int |
Returns an estimate of the percentage in the current content or ad up to which data is buffered, or 0 if no estimate is available. |
final long |
Returns an estimate of the position in the current content or ad up to which data is buffered, in milliseconds. |
final ImmutableList<CommandButton> |
@UnstableApiReturns the command buttons that are supported for the given |
final @Nullable SessionToken |
Returns the |
final long |
If #isPlayingAd() returns true}, returns an estimate of the content position in the current content up to which data is buffered, in milliseconds. |
final long |
If #isPlayingAd() returns true}, returns the duration of the current content in milliseconds, or C#TIME_UNSET if the duration is not known. |
final long |
If #isPlayingAd() returns true}, returns the content position that will be played once all ads in the ad group have finished playing, in milliseconds. |
final int |
If |
final int |
If |
final CueGroup |
Returns the current |
final long |
Returns the offset of the current playback position from the live edge in milliseconds, or |
final @Nullable Object |
Returns |
final @Nullable MediaItem |
Returns the currently playing |
final int |
Returns the index of the current |
final int |
Returns the index of the period currently being played. |
final long |
Returns the playback position in the current content or ad, in milliseconds, or the prospective position in milliseconds if the |
final Timeline |
Returns the current . |
final Tracks |
Returns the current tracks. |
final int |
This method is deprecated. Use |
final ImmutableList<CommandButton> |
Returns the custom layout. |
final DeviceInfo |
Gets the device information. |
final @IntRange(from = 0) int |
Gets the current volume of the device. |
final long |
Returns the duration of the current content or ad in milliseconds, or |
final long |
Returns the maximum position for which #seekToPrevious() seeks to the previous * , in milliseconds. |
final ImmutableList<CommandButton> |
Returns the media button preferences. |
final MediaItem |
getMediaItemAt(int index)Returns the |
final int |
Returns the number of |
final MediaMetadata |
Returns the current combined |
final int |
Returns the index of the that will be played if * #seekToNextMediaItem() is called, which may depend on the current repeat mode and whether shuffle mode is enabled. |
final int |
This method is deprecated. Use |
final boolean |
Whether playback will proceed when |
final PlaybackParameters |
Returns the currently active playback parameters. |
final int |
Returns the current |
final int |
Returns the reason why playback is suppressed even though |
final @Nullable PlaybackException |
Returns the error that caused playback to fail. |
final MediaMetadata |
Returns the playlist |
final int |
Returns the index of the that will be played if * #seekToPreviousMediaItem() is called, which may depend on the current repeat mode and whether shuffle mode is enabled. |
final int |
This method is deprecated. Use |
final int |
Returns the current |
final long |
Returns the #seekBack() increment. |
final long |
Returns the #seekForward() increment. |
final @Nullable PendingIntent |
Returns an intent for launching UI associated with the session if exists, or |
final Bundle |
Returns the session extras. |
final boolean |
Returns whether shuffling of media items is enabled. |
final Size |
Gets the size of the surface on which the video is rendered. |
final long |
Returns an estimate of the total buffered duration from the current position, in milliseconds. |
final TrackSelectionParameters |
Returns the parameters constraining the track selection. |
final VideoSize |
Gets the size of the video. |
final @FloatRange(from = 0, to = 1) float |
Returns the audio volume, with 0 being silence and 1 being unity gain (signal unchanged). |
final boolean |
Returns whether a next |
final boolean |
Returns whether a previous media item exists, which may depend on the current repeat mode and whether shuffle mode is enabled. |
final void |
This method is deprecated. Use |
final void |
increaseDeviceVolume(@C.VolumeFlags int flags)Increases the volume of the device. |
final boolean |
isCommandAvailable(@Player.Command int command)Returns whether the provided |
final boolean |
Returns whether this controller is connected to a |
final boolean |
Returns whether the current |
final boolean |
Returns whether the current |
final boolean |
Returns whether the current |
final boolean |
This method is deprecated. Use |
final boolean |
This method is deprecated. Use |
final boolean |
This method is deprecated. Use |
final boolean |
Gets whether the device is muted or not. |
final boolean |
Whether the player is currently loading the source. |
final boolean |
Returns whether the player is playing, i.e. |
final boolean |
Returns whether the player is currently playing an ad. |
final boolean |
isSessionCommandAvailable(Returns whether the |
final boolean |
isSessionCommandAvailable(SessionCommand sessionCommand)Returns whether the |
final void |
moveMediaItem(int currentIndex, int newIndex)Moves the media item at the current index to the new index. |
final void |
moveMediaItems(int fromIndex, int toIndex, int newIndex)Moves the media item range to the new index. |
final void |
mute()Sets the audio volume to 0. |
final void |
pause()Pauses playback. |
final void |
play()Resumes playback as soon as |
final void |
prepare()Prepares the player. |
final void |
release()Releases the connection between |
static void |
releaseFuture(Future<MediaController> controllerFuture)Releases the future controller returned by |
final void |
removeListener(Player.Listener listener)Unregister a listener registered through |
final void |
removeMediaItem(int index)Removes the media item at the given index of the playlist. |
final void |
removeMediaItems(int fromIndex, int toIndex)Removes a range of media items from the playlist. |
final void |
replaceMediaItem(int index, MediaItem mediaItem)Replaces the media item at the given index of the playlist. |
final void |
replaceMediaItems(Replaces the media items at the given range of the playlist. |
final void |
seekBack()Seeks back in the current by #getSeekBackIncrement() milliseconds. |
final void |
Seeks forward in the current by #getSeekForwardIncrement() milliseconds. |
final void |
seekTo(long positionMs)Seeks to a position specified in milliseconds in the current |
final void |
seekTo(int mediaItemIndex, long positionMs)Seeks to a position specified in milliseconds in the specified |
final void |
Seeks to the default position associated with the current |
final void |
seekToDefaultPosition(int mediaItemIndex)Seeks to the default position associated with the specified |
final void |
Seeks to a later position in the current or next (if available). |
final void |
Seeks to the default position of the next , which may depend on the current repeat mode and whether shuffle mode is enabled. |
final void |
Seeks to an earlier position in the current or previous (if available). |
final void |
Seeks to the default position of the previous , which may depend on the current repeat mode and whether shuffle mode is enabled. |
final ListenableFuture<SessionResult> |
sendCustomCommand(SessionCommand command, Bundle args)Sends a custom command to the session. |
final ListenableFuture<SessionResult> |
@UnstableApiSends a custom command to the session. |
final ListenableFuture<SessionResult> |
@UnstableApiSends a custom command to the session for the given |
final ListenableFuture<SessionResult> |
@UnstableApiSends a custom command to the session for the given |
final void |
setAudioAttributes(Sets the attributes for audio playback, used by the underlying audio track. |
final void |
This method is deprecated. Use |
final void |
setDeviceMuted(boolean muted, @C.VolumeFlags int flags)Sets the mute state of the device. |
final void |
This method is deprecated. Use |
final void |
setDeviceVolume(@IntRange(from = 0) int volume, @C.VolumeFlags int flags)Sets the volume of the device with volume flags. |
final void |
setMediaItem(MediaItem mediaItem)Clears the playlist, adds the specified |
final void |
setMediaItem(MediaItem mediaItem, boolean resetPosition)Clears the playlist and adds the specified |
final void |
setMediaItem(MediaItem mediaItem, long startPositionMs)Clears the playlist and adds the specified |
final void |
setMediaItems(List<MediaItem> mediaItems)Clears the playlist, adds the specified |
final void |
setMediaItems(List<MediaItem> mediaItems, boolean resetPosition)Clears the playlist and adds the specified |
final void |
setMediaItems(Clears the playlist and adds the specified |
final void |
setPlayWhenReady(boolean playWhenReady)Sets whether playback should proceed when |
final void |
setPlaybackParameters(PlaybackParameters playbackParameters)Attempts to set the playback parameters. |
final void |
setPlaybackSpeed(float speed)Changes the rate at which playback occurs. |
final void |
setPlaylistMetadata(MediaMetadata playlistMetadata)Sets the playlist |
final ListenableFuture<SessionResult> |
Requests that the connected |
final ListenableFuture<SessionResult> |
Requests that the connected |
final void |
setRepeatMode(@Player.RepeatMode int repeatMode)Sets the |
final void |
setShuffleModeEnabled(boolean shuffleModeEnabled)Sets whether shuffling of media items is enabled. |
final void |
setTrackSelectionParameters(TrackSelectionParameters parameters)Sets the parameters constraining the track selection. |
final void |
setVideoSurface(@Nullable Surface surface)Sets the |
final void |
setVideoSurfaceHolder(@Nullable SurfaceHolder surfaceHolder)Sets the |
final void |
setVideoSurfaceView(@Nullable SurfaceView surfaceView)Sets the |
final void |
setVideoTextureView(@Nullable TextureView textureView)Sets the |
final void |
setVolume(@FloatRange(from = 0, to = 1) float volume)Sets the audio volume, valid values are between 0 (silence) and 1 (unity gain, signal unchanged), inclusive. |
final void |
stop()Stops playback without resetting the playlist. |
final void |
unmute()If the audio volume is 0, sets the audio volume to a non-zero value decided by the Player to be the most appropriate. |
Inherited Constants |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
Constants
DEFAULT_PLATFORM_CALLBACK_AGGREGATION_TIMEOUT_MS
@UnstableApi
protected static final long DEFAULT_PLATFORM_CALLBACK_AGGREGATION_TIMEOUT_MS = 100
KEY_MEDIA_NOTIFICATION_CONTROLLER_FLAG
@UnstableApi
public static final String KEY_MEDIA_NOTIFICATION_CONTROLLER_FLAG = "androidx.media3.session.MediaNotificationManager"
Key to mark the connection hints of the media notification controller.
For a controller to be recognized by the session as the media notification controller, this key needs to be used to set a boolean flag in the connection hints to true. Only an internal controller that has the same package name as the session can be used as a media notification controller.
When using a session within a MediaSessionService or MediaLibraryService, the service connects a media notification controller automatically. Apps can do this for standalone session to configure the platform session in the same way.
RELEASE_UNBIND_TIMEOUT_MS
@UnstableApi
public static final long RELEASE_UNBIND_TIMEOUT_MS = 30000
The timeout for handling pending commands after calling release. If the timeout is reached, the controller is unbound from the session service even if commands are still pending.
Public methods
addListener
public final void addListener(Player.Listener listener)
Registers a listener to receive all events from the player.
The listener's methods will be called on the thread associated with getApplicationLooper.
This method can be called from any thread.
| Parameters | |
|---|---|
Player.Listener listener |
The listener to register. |
addMediaItem
public final void addMediaItem(MediaItem mediaItem)
Adds a media item to the end of the playlist.
This method must only be called if COMMAND_CHANGE_MEDIA_ITEMS is available.
addMediaItem
public final void addMediaItem(int index, MediaItem mediaItem)
Adds a media item at the given index of the playlist.
This method must only be called if COMMAND_CHANGE_MEDIA_ITEMS is available.
addMediaItems
public final void addMediaItems(List<MediaItem> mediaItems)
Adds a list of media items to the end of the playlist.
This method must only be called if COMMAND_CHANGE_MEDIA_ITEMS is available.
| Parameters | |
|---|---|
List<MediaItem> mediaItems |
The |
addMediaItems
public final void addMediaItems(int index, List<MediaItem> mediaItems)
Adds a list of media items at the given index of the playlist.
This method must only be called if COMMAND_CHANGE_MEDIA_ITEMS is available.
| Parameters | |
|---|---|
int index |
The index at which to add the media items. If the index is larger than the size of the playlist, the media items are added to the end of the playlist. |
List<MediaItem> mediaItems |
The |
canAdvertiseSession
public final boolean canAdvertiseSession()
Returns whether the player can be used to advertise a media session.
The MediaController returns false.
clearMediaItems
public final void clearMediaItems()
Clears the playlist.
This method must only be called if COMMAND_CHANGE_MEDIA_ITEMS is available.
clearVideoSurface
public final void clearVideoSurface()
Clears any Surface, SurfaceHolder, SurfaceView or TextureView currently set on the player.
This method must only be called if COMMAND_SET_VIDEO_SURFACE is available.
clearVideoSurface
public final void clearVideoSurface(@Nullable Surface surface)
Clears the Surface onto which video is being rendered if it matches the one passed. Else does nothing.
This method must only be called if COMMAND_SET_VIDEO_SURFACE is available.
clearVideoSurfaceHolder
public final void clearVideoSurfaceHolder(@Nullable SurfaceHolder surfaceHolder)
Clears the SurfaceHolder that holds the Surface onto which video is being rendered if it matches the one passed. Else does nothing.
This method must only be called if COMMAND_SET_VIDEO_SURFACE is available.
| Parameters | |
|---|---|
@Nullable SurfaceHolder surfaceHolder |
The surface holder to clear. |
clearVideoSurfaceView
public final void clearVideoSurfaceView(@Nullable SurfaceView surfaceView)
Clears the SurfaceView onto which video is being rendered if it matches the one passed. Else does nothing.
This method must only be called if COMMAND_SET_VIDEO_SURFACE is available.
| Parameters | |
|---|---|
@Nullable SurfaceView surfaceView |
The texture view to clear. |
clearVideoTextureView
public final void clearVideoTextureView(@Nullable TextureView textureView)
Clears the TextureView onto which video is being rendered if it matches the one passed. Else does nothing.
This method must only be called if COMMAND_SET_VIDEO_SURFACE is available.
| Parameters | |
|---|---|
@Nullable TextureView textureView |
The texture view to clear. |
decreaseDeviceVolume
public final void decreaseDeviceVolume(@C.VolumeFlags int flags)
Decreases the volume of the device.
The getDeviceVolume device volume cannot be decreased below minVolume.
Note that this method affects the device volume. To change the volume of the current stream only, use setVolume.
This method must only be called if COMMAND_ADJUST_DEVICE_VOLUME_WITH_FLAGS is available.
| Parameters | |
|---|---|
@C.VolumeFlags int flags |
Either 0 or a bitwise combination of one or more |
getApplicationLooper
public final Looper getApplicationLooper()
Returns the Looper associated with the application thread that's used to access the player and on which player events are received.
This method can be called from any thread.
getAudioAttributes
public final AudioAttributes getAudioAttributes()
Returns the attributes for audio playback.
This method must only be called if COMMAND_GET_AUDIO_ATTRIBUTES is available.
| See also | |
|---|---|
onAudioAttributesChanged |
getAudioSessionId
@UnstableApi
public final int getAudioSessionId()
Returns the audio session identifier, or AUDIO_SESSION_ID_UNSET if not set.
| See also | |
|---|---|
onAudioSessionIdChanged |
getAvailableCommands
public final Player.Commands getAvailableCommands()
Returns the player's currently available Commands.
The returned Commands are not updated when available commands change. Use onAvailableCommandsChanged to get an update when the available commands change.
| Returns | |
|---|---|
Player.Commands |
The currently available |
| See also | |
|---|---|
onAvailableCommandsChanged |
getAvailableSessionCommands
public final SessionCommands getAvailableSessionCommands()
Returns the current available session commands from onAvailableSessionCommandsChanged, or EMPTY if it is not connected.
| Returns | |
|---|---|
SessionCommands |
The available session commands. |
getBufferedPercentage
public final @IntRange(from = 0, to = 100) int getBufferedPercentage()
Returns an estimate of the percentage in the current content or ad up to which data is buffered, or 0 if no estimate is available.
getBufferedPosition
public final long getBufferedPosition()
Returns an estimate of the position in the current content or ad up to which data is buffered, in milliseconds.
This method must only be called if COMMAND_GET_CURRENT_MEDIA_ITEM is available.
getCommandButtonsForMediaItem
@UnstableApi
public final ImmutableList<CommandButton> getCommandButtonsForMediaItem(MediaItem mediaItem)
Returns the command buttons that are supported for the given MediaItem.
| Parameters | |
|---|---|
MediaItem mediaItem |
The media item for which to get command buttons. |
| Returns | |
|---|---|
ImmutableList<CommandButton> |
The |
getConnectedToken
public final @Nullable SessionToken getConnectedToken()
Returns the SessionToken of the connected session, or null if it is not connected.
This may differ from the SessionToken from the constructor. For example, if the controller is created with the token for MediaSessionService, this will return a token for the MediaSession in the service.
getContentBufferedPosition
public final long getContentBufferedPosition()
If #isPlayingAd() returns true}, returns an estimate of the content position in the current content up to which data is buffered, in milliseconds. If there is no ad playing, the returned position is the same as that returned by #getBufferedPosition().
This method must only be called if #COMMAND_GET_CURRENT_MEDIA_ITEM is * #getAvailableCommands() available.
Interoperability: When connected to
android.support.v4.media.session.MediaSessionCompat, it's the same as getBufferedPosition because content buffered position isn't available.
getContentDuration
public final long getContentDuration()
If #isPlayingAd() returns true}, returns the duration of the current content in milliseconds, or C#TIME_UNSET if the duration is not known. If there is no ad playing, the returned duration is the same as that returned by #getDuration().
This method must only be called if #COMMAND_GET_CURRENT_MEDIA_ITEM is * #getAvailableCommands() available.
Interoperability: When connected to
android.support.v4.media.session.MediaSessionCompat, it's the same as getDuration to match the behavior with getContentPosition and getContentBufferedPosition.
getContentPosition
public final long getContentPosition()
If #isPlayingAd() returns true}, returns the content position that will be played once all ads in the ad group have finished playing, in milliseconds. If there is no ad playing, the returned position is the same as that returned by #getCurrentPosition().
This method must only be called if #COMMAND_GET_CURRENT_MEDIA_ITEM is * #getAvailableCommands() available.
Interoperability: When connected to
android.support.v4.media.session.MediaSessionCompat, it's the same as getCurrentPosition because content position isn't available.
getCurrentAdGroupIndex
public final int getCurrentAdGroupIndex()
If isPlayingAd returns true, returns the index of the ad group in the period currently being played. Returns INDEX_UNSET otherwise.
This method must only be called if COMMAND_GET_CURRENT_MEDIA_ITEM is available.
getCurrentAdIndexInAdGroup
public final int getCurrentAdIndexInAdGroup()
If isPlayingAd returns true, returns the index of the ad in its ad group. Returns INDEX_UNSET otherwise.
This method must only be called if COMMAND_GET_CURRENT_MEDIA_ITEM is available.
getCurrentCues
public final CueGroup getCurrentCues()
Returns the current CueGroup.
This method must only be called if COMMAND_GET_TEXT is available.
| See also | |
|---|---|
onCues |
getCurrentLiveOffset
public final long getCurrentLiveOffset()
Returns the offset of the current playback position from the live edge in milliseconds, or TIME_UNSET if the current MediaItemisn't live or the offset is unknown.
The offset is calculated as currentTime - playbackPosition, so should usually be positive.
Note that this offset may rely on an accurate local time, so this method may return an incorrect value if the difference between system clock and server clock is unknown.
This method must only be called if COMMAND_GET_CURRENT_MEDIA_ITEM is available.
getCurrentMediaItem
public final @Nullable MediaItem getCurrentMediaItem()
Returns the currently playing MediaItem. May be null if the timeline is empty.
This method must only be called if COMMAND_GET_CURRENT_MEDIA_ITEM is available.
| See also | |
|---|---|
onMediaItemTransition |
getCurrentMediaItemIndex
public final int getCurrentMediaItemIndex()
Returns the index of the current MediaItem in the timeline, or the prospective index if the current timeline is empty.
This method must only be called if COMMAND_GET_TIMELINE is available.
getCurrentPeriodIndex
public final int getCurrentPeriodIndex()
Returns the index of the period currently being played.
This method must only be called if COMMAND_GET_TIMELINE is available.
getCurrentPosition
public final long getCurrentPosition()
Returns the playback position in the current content or ad, in milliseconds, or the prospective position in milliseconds if the current timeline is empty.
This method must only be called if COMMAND_GET_CURRENT_MEDIA_ITEM is available.
getCurrentTimeline
public final Timeline getCurrentTimeline()
Returns the current . Never null, but may be empty.
This method must only be called if #COMMAND_GET_TIMELINE is * #getAvailableCommands() available.
getCurrentTracks
public final Tracks getCurrentTracks()
Returns the current tracks.
This method must only be called if COMMAND_GET_TRACKS is available.
| See also | |
|---|---|
onTracksChanged |
getCustomLayout
public final ImmutableList<CommandButton> getCustomLayout()
Returns the custom layout.
This method will be deprecated, prefer to use getMediaButtonPreferences instead. Note that the media button preferences use slots to define the allowed button placement.
After being connected, a change of the custom layout is reported with onCustomLayoutChanged.
Note that the enabled flag is set to false if the available commands do not allow to use a button.
| Returns | |
|---|---|
ImmutableList<CommandButton> |
The custom layout. |
getDeviceVolume
public final @IntRange(from = 0) int getDeviceVolume()
Gets the current volume of the device.
For devices with local playback, the volume returned by this method varies according to the current stream type. The stream type is determined by getStreamType.
For devices with remote playback, the volume of the remote device is returned.
Note that this method returns the volume of the device. To check the current stream volume, use getVolume.
This method must only be called if COMMAND_GET_DEVICE_VOLUME is available.
| See also | |
|---|---|
onDeviceVolumeChanged |
getDuration
public final long getDuration()
Returns the duration of the current content or ad in milliseconds, or TIME_UNSET if the duration is not known.
This method must only be called if COMMAND_GET_CURRENT_MEDIA_ITEM is available.
getMaxSeekToPreviousPosition
public final long getMaxSeekToPreviousPosition()
Returns the maximum position for which #seekToPrevious() seeks to the previous * , in milliseconds.
Interoperability: When connected to
android.support.v4.media.session.MediaSessionCompat, it always returns 0.
getMediaButtonPreferences
@UnstableApi
public final ImmutableList<CommandButton> getMediaButtonPreferences()
Returns the media button preferences.
After being connected, a change of the media button preferences is reported with onMediaButtonPreferencesChanged.
Note that the enabled flag is set to false if the available commands do not allow to use a button.
| Returns | |
|---|---|
ImmutableList<CommandButton> |
The media button preferences. |
getMediaItemAt
public final MediaItem getMediaItemAt(int index)
Returns the MediaItem at the given index.
This method must only be called if COMMAND_GET_TIMELINE is available.
getMediaItemCount
public final int getMediaItemCount()
Returns the number of media items in the playlist.
This method must only be called if COMMAND_GET_TIMELINE is available.
getMediaMetadata
public final MediaMetadata getMediaMetadata()
Returns the current combined MediaMetadata, or EMPTY if not supported.
This MediaMetadata is a combination of the MediaItem metadata, the static metadata in the media's Format, and any timed metadata that has been parsed from the media and output via onMetadata. If a field is populated in the mediaMetadata, it will be prioritised above the same field coming from static or timed metadata.
This method must only be called if COMMAND_GET_METADATA is available.
| See also | |
|---|---|
onMediaMetadataChanged |
getNextMediaItemIndex
public final int getNextMediaItemIndex()
Returns the index of the that will be played if * #seekToNextMediaItem() is called, which may depend on the current repeat mode and whether shuffle mode is enabled. Returns C#INDEX_UNSET if #hasNextMediaItem() is *false.
Note: When the repeat mode is #REPEAT_MODE_ONE, this method behaves the same as when the current repeat mode is #REPEAT_MODE_OFF. See #REPEAT_MODE_ONE for more details.
This method must only be called if #COMMAND_GET_TIMELINE is * #getAvailableCommands() available.
Interoperability: When connected to
android.support.v4.media.session.MediaSessionCompat, this will always return INDEX_UNSET even when hasNextMediaItem is true.
getPlayWhenReady
public final boolean getPlayWhenReady()
Whether playback will proceed when getPlaybackState == STATE_READY.
| Returns | |
|---|---|
boolean |
Whether playback will proceed when ready. |
| See also | |
|---|---|
onPlayWhenReadyChanged |
getPlaybackParameters
public final PlaybackParameters getPlaybackParameters()
Returns the currently active playback parameters.
| See also | |
|---|---|
onPlaybackParametersChanged |
getPlaybackState
@Player.State
public final int getPlaybackState()
Returns the current playback state of the player.
| Returns | |
|---|---|
int |
The current |
| See also | |
|---|---|
onPlaybackStateChanged |
getPlaybackSuppressionReason
@Player.PlaybackSuppressionReason
public final int getPlaybackSuppressionReason()
Returns the reason why playback is suppressed even though getPlayWhenReady is
true, or PLAYBACK_SUPPRESSION_REASON_NONE if playback is not suppressed.
| Returns | |
|---|---|
int |
The current |
| See also | |
|---|---|
onPlaybackSuppressionReasonChanged |
getPlayerError
public final @Nullable PlaybackException getPlayerError()
Returns the error that caused playback to fail. This is the same error that will have been reported via onPlayerError at the time of failure. It can be queried using this method until the player is re-prepared.
Note that this method will always return null if getPlaybackState is not STATE_IDLE.
| Returns | |
|---|---|
@Nullable PlaybackException |
The error, or |
| See also | |
|---|---|
onPlayerError |
getPlaylistMetadata
public final MediaMetadata getPlaylistMetadata()
Returns the playlist MediaMetadata, as set by setPlaylistMetadata, or EMPTY if not supported.
This method must only be called if COMMAND_GET_METADATA is available.
| See also | |
|---|---|
onPlaylistMetadataChanged |
getPreviousMediaItemIndex
public final int getPreviousMediaItemIndex()
Returns the index of the that will be played if * #seekToPreviousMediaItem() is called, which may depend on the current repeat mode and whether shuffle mode is enabled. Returns C#INDEX_UNSET if #hasPreviousMediaItem() is false}.
Note: When the repeat mode is #REPEAT_MODE_ONE, this method behaves the same as when the current repeat mode is #REPEAT_MODE_OFF. See #REPEAT_MODE_ONE for more details.
This method must only be called if #COMMAND_GET_TIMELINE is * #getAvailableCommands() available.
Interoperability: When connected to
android.support.v4.media.session.MediaSessionCompat, this will always return INDEX_UNSET even when hasPreviousMediaItem is true.
getRepeatMode
@Player.RepeatMode
public final int getRepeatMode()
Returns the current RepeatMode used for playback.
| Returns | |
|---|---|
int |
The current repeat mode. |
| See also | |
|---|---|
onRepeatModeChanged |
getSeekBackIncrement
public final long getSeekBackIncrement()
Returns the #seekBack() increment.
Interoperability: When connected to
android.support.v4.media.session.MediaSessionCompat, it returns 0.
getSeekForwardIncrement
public final long getSeekForwardIncrement()
Returns the #seekForward() increment.
Interoperability: When connected to
android.support.v4.media.session.MediaSessionCompat, it returns 0.
getSessionActivity
public final @Nullable PendingIntent getSessionActivity()
Returns an intent for launching UI associated with the session if exists, or null.
getSessionExtras
public final Bundle getSessionExtras()
Returns the session extras.
After being connected, onExtrasChanged is called when the extras on the session are set.
| Returns | |
|---|---|
Bundle |
The session extras. |
getShuffleModeEnabled
public final boolean getShuffleModeEnabled()
Returns whether shuffling of media items is enabled.
| See also | |
|---|---|
onShuffleModeEnabledChanged |
getSurfaceSize
@UnstableApi
public final Size getSurfaceSize()
Gets the size of the surface on which the video is rendered.
| See also | |
|---|---|
onSurfaceSizeChanged |
getTotalBufferedDuration
public final long getTotalBufferedDuration()
Returns an estimate of the total buffered duration from the current position, in milliseconds. This includes pre-buffered data for subsequent ads and media items.
This method must only be called if COMMAND_GET_CURRENT_MEDIA_ITEM is available.
getTrackSelectionParameters
public final TrackSelectionParameters getTrackSelectionParameters()
Returns the parameters constraining the track selection.
| See also | |
|---|---|
onTrackSelectionParametersChanged |
} |
getVideoSize
public final VideoSize getVideoSize()
Gets the size of the video.
The video's width and height are 0 if there is no supported video track or its size has not been determined yet.
| See also | |
|---|---|
onVideoSizeChanged |
getVolume
public final @FloatRange(from = 0, to = 1) float getVolume()
Returns the audio volume, with 0 being silence and 1 being unity gain (signal unchanged).
This method must only be called if COMMAND_GET_VOLUME is available.
| Returns | |
|---|---|
@FloatRange(from = 0, to = 1) float |
The linear gain applied to all audio channels. |
| See also | |
|---|---|
onVolumeChanged |
hasNextMediaItem
public final boolean hasNextMediaItem()
Returns whether a next MediaItem exists, which may depend on the current repeat mode and whether shuffle mode is enabled.
Note: When the repeat mode is REPEAT_MODE_ONE, this method behaves the same as when the current repeat mode is REPEAT_MODE_OFF. See REPEAT_MODE_ONE for more details.
This method must only be called if COMMAND_GET_TIMELINE is available.
hasPreviousMediaItem
public final boolean hasPreviousMediaItem()
Returns whether a previous media item exists, which may depend on the current repeat mode and whether shuffle mode is enabled.
Note: When the repeat mode is REPEAT_MODE_ONE, this method behaves the same as when the current repeat mode is REPEAT_MODE_OFF. See REPEAT_MODE_ONE for more details.
This method must only be called if COMMAND_GET_TIMELINE is available.
increaseDeviceVolume
public final void increaseDeviceVolume(@C.VolumeFlags int flags)
Increases the volume of the device.
The getDeviceVolume device volume cannot be increased above maxVolume, if defined.
Note that this method affects the device volume. To change the volume of the current stream only, use setVolume.
This method must only be called if COMMAND_ADJUST_DEVICE_VOLUME_WITH_FLAGS is available.
| Parameters | |
|---|---|
@C.VolumeFlags int flags |
Either 0 or a bitwise combination of one or more |
isCommandAvailable
public final boolean isCommandAvailable(@Player.Command int command)
Returns whether the provided Command is available.
This method does not execute the command.
| Parameters | |
|---|---|
@Player.Command int command |
A |
| Returns | |
|---|---|
boolean |
Whether the |
| See also | |
|---|---|
onAvailableCommandsChanged |
isConnected
public final boolean isConnected()
Returns whether this controller is connected to a MediaSession or not.
isCurrentMediaItemDynamic
public final boolean isCurrentMediaItemDynamic()
Returns whether the current MediaItem is dynamic (may change when the Timeline is updated), or false if the Timeline is empty.
This method must only be called if COMMAND_GET_CURRENT_MEDIA_ITEM is available.
| See also | |
|---|---|
isDynamic |
isCurrentMediaItemLive
public final boolean isCurrentMediaItemLive()
Returns whether the current MediaItem is live, or false if the Timeline is empty.
This method must only be called if COMMAND_GET_CURRENT_MEDIA_ITEM is available.
| See also | |
|---|---|
isLive |
isCurrentMediaItemSeekable
public final boolean isCurrentMediaItemSeekable()
Returns whether the current MediaItem is seekable, or false if the Timeline is empty.
This method must only be called if COMMAND_GET_CURRENT_MEDIA_ITEM is available.
| See also | |
|---|---|
isSeekable |
isDeviceMuted
public final boolean isDeviceMuted()
Gets whether the device is muted or not.
Note that this method returns the mute state of the device. To check if the current stream is muted, use getVolume() == 0.
This method must only be called if COMMAND_GET_DEVICE_VOLUME is available.
| See also | |
|---|---|
onDeviceVolumeChanged |
isLoading
public final boolean isLoading()
Whether the player is currently loading the source.
| Returns | |
|---|---|
boolean |
Whether the player is currently loading the source. |
| See also | |
|---|---|
onIsLoadingChanged |
isPlaying
public final boolean isPlaying()
Returns whether the player is playing, i.e. getCurrentPosition is advancing.
If false, then at least one of the following is true:
- The
playback stateis notready. - There is no
intention to play. - Playback is
suppressed for other reasons.
| Returns | |
|---|---|
boolean |
Whether the player is playing. |
| See also | |
|---|---|
onIsPlayingChanged |
isPlayingAd
public final boolean isPlayingAd()
Returns whether the player is currently playing an ad.
This method must only be called if COMMAND_GET_CURRENT_MEDIA_ITEM is available.
isSessionCommandAvailable
public final boolean isSessionCommandAvailable(
@SessionCommand.CommandCode int sessionCommandCode
)
Returns whether the SessionCommand.CommandCode is available. The
sessionCommandCode must not be COMMAND_CODE_CUSTOM. Use isSessionCommandAvailable for custom commands.
isSessionCommandAvailable
public final boolean isSessionCommandAvailable(SessionCommand sessionCommand)
Returns whether the SessionCommand is available.
moveMediaItem
public final void moveMediaItem(int currentIndex, int newIndex)
Moves the media item at the current index to the new index.
This method must only be called if COMMAND_CHANGE_MEDIA_ITEMS is available.
| Parameters | |
|---|---|
int currentIndex |
The current index of the media item to move. If the index is larger than the size of the playlist, the request is ignored. |
int newIndex |
The new index of the media item. If the new index is larger than the size of the playlist the item is moved to the end of the playlist. |
moveMediaItems
public final void moveMediaItems(int fromIndex, int toIndex, int newIndex)
Moves the media item range to the new index.
This method must only be called if COMMAND_CHANGE_MEDIA_ITEMS is available.
| Parameters | |
|---|---|
int fromIndex |
The start of the range to move. If the index is larger than the size of the playlist, the request is ignored. |
int toIndex |
The first item not to be included in the range (exclusive). If the index is larger than the size of the playlist, items up to the end of the playlist are moved. |
int newIndex |
The new index of the first media item of the range. If the new index is larger than the size of the remaining playlist after removing the range, the range is moved to the end of the playlist. |
mute
public final void mute()
Sets the audio volume to 0.
This method must only be called if COMMAND_SET_VOLUME is available.
pause
public final void pause()
Pauses playback. Equivalent to setPlayWhenReady(false).
This method must only be called if COMMAND_PLAY_PAUSE is available.
play
public final void play()
Resumes playback as soon as getPlaybackState == STATE_READY. Equivalent to setPlayWhenReady(true).
This method must only be called if COMMAND_PLAY_PAUSE is available.
prepare
public final void prepare()
Prepares the player.
This method must only be called if COMMAND_PREPARE is available.
This will move the player out of idle state and the player will start loading media and acquire resources needed for playback.
release
public final void release()
Releases the connection between MediaController and MediaSession. This method must be called when the controller is no longer required. The controller must not be used after calling this method.
This method does not call release of the underlying player in the session.
releaseFuture
public static void releaseFuture(Future<MediaController> controllerFuture)
Releases the future controller returned by buildAsync. It makes sure that the controller is released by canceling the future if the future is not yet done.
Must be called on the application thread of the media controller.
removeListener
public final void removeListener(Player.Listener listener)
Unregister a listener registered through addListener. The listener will no longer receive events.
| Parameters | |
|---|---|
Player.Listener listener |
The listener to unregister. |
removeMediaItem
public final void removeMediaItem(int index)
Removes the media item at the given index of the playlist.
This method must only be called if COMMAND_CHANGE_MEDIA_ITEMS is available.
| Parameters | |
|---|---|
int index |
The index at which to remove the media item. If the index is larger than the size of the playlist, the request is ignored. |
removeMediaItems
public final void removeMediaItems(int fromIndex, int toIndex)
Removes a range of media items from the playlist.
This method must only be called if COMMAND_CHANGE_MEDIA_ITEMS is available.
| Parameters | |
|---|---|
int fromIndex |
The index at which to start removing media items. If the index is larger than the size of the playlist, the request is ignored. |
int toIndex |
The index of the first item to be kept (exclusive). If the index is larger than the size of the playlist, media items up to the end of the playlist are removed. |
replaceMediaItem
public final void replaceMediaItem(int index, MediaItem mediaItem)
Replaces the media item at the given index of the playlist.
Implementations of this method may attempt to seamlessly continue playback if the currently playing media item is replaced with a compatible one (e.g. same URL, only metadata has changed).
This method must only be called if COMMAND_CHANGE_MEDIA_ITEMS is available.
replaceMediaItems
public final void replaceMediaItems(
int fromIndex,
int toIndex,
List<MediaItem> mediaItems
)
Replaces the media items at the given range of the playlist.
Implementations of this method may attempt to seamlessly continue playback if the currently playing media item is replaced with a compatible one (e.g. same URL, only metadata has changed).
This method must only be called if COMMAND_CHANGE_MEDIA_ITEMS is available.
Note that it is possible to replace a range with an arbitrary number of new items, so that the number of removed items defined by fromIndex and toIndex does not have to match the number of added items defined by mediaItems. As result, it may also change the index of subsequent items not touched by this operation.
| Parameters | |
|---|---|
int fromIndex |
The start of the range. If the index is larger than the size of the playlist, the request is ignored. |
int toIndex |
The first item not to be included in the range (exclusive). If the index is larger than the size of the playlist, items up to the end of the playlist are replaced. |
List<MediaItem> mediaItems |
The |
seekBack
public final void seekBack()
Seeks back in the current by #getSeekBackIncrement() milliseconds.
This method must only be called if #COMMAND_SEEK_BACK is * #getAvailableCommands() available.
Interoperability: When connected to
android.support.v4.media.session.MediaSessionCompat, it calls
android.support.v4.media.session.MediaControllerCompat.TransportControls.rewind().
seekForward
public final void seekForward()
Seeks forward in the current by #getSeekForwardIncrement() milliseconds.
This method must only be called if #COMMAND_SEEK_FORWARD is * #getAvailableCommands() available.
Interoperability: When connected to
android.support.v4.media.session.MediaSessionCompat, it calls
android.support.v4.media.session.MediaControllerCompat.TransportControls.fastForward().
seekTo
public final void seekTo(long positionMs)
Seeks to a position specified in milliseconds in the current MediaItem.
This method must only be called if COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM is available.
| Parameters | |
|---|---|
long positionMs |
The seek position in the current |
seekTo
public final void seekTo(int mediaItemIndex, long positionMs)
Seeks to a position specified in milliseconds in the specified MediaItem.
This method must only be called if COMMAND_SEEK_TO_MEDIA_ITEM is available.
| Parameters | |
|---|---|
int mediaItemIndex |
The index of the |
long positionMs |
The seek position in the specified |
seekToDefaultPosition
public final void seekToDefaultPosition()
Seeks to the default position associated with the current MediaItem. The position can depend on the type of media being played. For live streams it will typically be the live edge. For other streams it will typically be the start.
This method must only be called if COMMAND_SEEK_TO_DEFAULT_POSITION is available.
seekToDefaultPosition
public final void seekToDefaultPosition(int mediaItemIndex)
Seeks to the default position associated with the specified MediaItem. The position can depend on the type of media being played. For live streams it will typically be the live edge. For other streams it will typically be the start.
This method must only be called if COMMAND_SEEK_TO_MEDIA_ITEM is available.
| Parameters | |
|---|---|
int mediaItemIndex |
The index of the |
seekToNext
public final void seekToNext()
Seeks to a later position in the current or next (if available). More precisely:
- If the timeline is empty or seeking is not possible, does nothing.
- Otherwise, if #hasNextMediaItem() a next media item exists, seeks to the default position of the next .
- Otherwise, if the current is #isCurrentMediaItemLive() live and has not ended, seeks to the live edge of the current .
- Otherwise, does nothing.
This method must only be called if #COMMAND_SEEK_TO_NEXT is * #getAvailableCommands() available.
Interoperability: When connected to
android.support.v4.media.session.MediaSessionCompat, it won't update the current media item index immediately because the previous media item index is unknown.
seekToNextMediaItem
public final void seekToNextMediaItem()
Seeks to the default position of the next , which may depend on the current repeat mode and whether shuffle mode is enabled. Does nothing if #hasNextMediaItem() is false}.
Note: When the repeat mode is #REPEAT_MODE_ONE, this method behaves the same as when the current repeat mode is #REPEAT_MODE_OFF. See #REPEAT_MODE_ONE for more details.
This method must only be called if #COMMAND_SEEK_TO_NEXT_MEDIA_ITEM is * #getAvailableCommands() available.
Interoperability: When connected to
android.support.v4.media.session.MediaSessionCompat, it's the same as seekToNext.
seekToPrevious
public final void seekToPrevious()
Seeks to an earlier position in the current or previous (if available). More precisely:
- If the timeline is empty or seeking is not possible, does nothing.
- Otherwise, if the current is #isCurrentMediaItemLive() live and #isCurrentMediaItemSeekable() unseekable, then:
- If #hasPreviousMediaItem() a previous media item exists, seeks to the default position of the previous media item.
- Otherwise, does nothing.
- Otherwise, if #hasPreviousMediaItem() a previous media item exists and the #getCurrentPosition() current position is less than * #getMaxSeekToPreviousPosition(), seeks to the default position of the previous * .
- Otherwise, seeks to 0 in the current .
This method must only be called if #COMMAND_SEEK_TO_PREVIOUS is * #getAvailableCommands() available.
Interoperability: When connected to
android.support.v4.media.session.MediaSessionCompat, it won't update the current media item index immediately because the previous media item index is unknown.
seekToPreviousMediaItem
public final void seekToPreviousMediaItem()
Seeks to the default position of the previous , which may depend on the current repeat mode and whether shuffle mode is enabled. Does nothing if * #hasPreviousMediaItem() is false}.
Note: When the repeat mode is #REPEAT_MODE_ONE, this method behaves the same as when the current repeat mode is #REPEAT_MODE_OFF. See #REPEAT_MODE_ONE for more details.
This method must only be called if #COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM is #getAvailableCommands() available.
Interoperability: When connected to
android.support.v4.media.session.MediaSessionCompat, it's the same as seekToPrevious.
sendCustomCommand
public final ListenableFuture<SessionResult> sendCustomCommand(SessionCommand command, Bundle args)
Sends a custom command to the session.
A command is not accepted if it is not a custom command or the command is not in the list of available session commands.
Interoperability: When connected to
android.support.v4.media.session.MediaSessionCompat, resultCode will return the custom result code from the android.os.ResultReceiver#onReceiveResult(int,
Bundle) instead of the standard result codes defined in the SessionResult.
| Parameters | |
|---|---|
SessionCommand command |
The custom command. |
Bundle args |
The additional arguments. May be empty. |
| Returns | |
|---|---|
ListenableFuture<SessionResult> |
A |
sendCustomCommand
@UnstableApi
public final ListenableFuture<SessionResult> sendCustomCommand(
SessionCommand command,
Bundle args,
@Nullable MediaController.ProgressListener progressListener
)
Sends a custom command to the session.
A controller can request progress updates by passing in a non-null ProgressListener. Whether or not the session sends progress updates depends on the implementation of the session callback that responds to the given SessionCommand.
Interoperability: When connected to
android.support.v4.media.session.MediaSessionCompat, resultCode will return the custom result code from the android.os.ResultReceiver#onReceiveResult(int,
Bundle) instead of the standard result codes defined in the SessionResult.
| Parameters | |
|---|---|
SessionCommand command |
The custom command. |
Bundle args |
The additional arguments. May be empty. |
@Nullable MediaController.ProgressListener progressListener |
A |
| Returns | |
|---|---|
ListenableFuture<SessionResult> |
A |
sendCustomCommand
@UnstableApi
public final ListenableFuture<SessionResult> sendCustomCommand(
SessionCommand command,
MediaItem mediaItem,
Bundle args
)
Sends a custom command to the session for the given media item.
Calling this method is equivalent to calling sendCustomCommand and including the media ID in the argument bundle with key EXTRA_KEY_MEDIA_ID.
A command is not accepted if it is not a custom command or the command is not in the list of available session commands.
Interoperability: When sending a custom command to
android.support.v4.media.session.MediaSessionCompat, resultCode will always be RESULT_SUCCESS because the session has no way to send a result back from onCustomAction.
| Parameters | |
|---|---|
SessionCommand command |
The custom command. |
MediaItem mediaItem |
The media item for which the command is sent. |
Bundle args |
The additional arguments. May be empty. |
| Returns | |
|---|---|
ListenableFuture<SessionResult> |
A |
sendCustomCommand
@UnstableApi
public final ListenableFuture<SessionResult> sendCustomCommand(
SessionCommand command,
MediaItem mediaItem,
Bundle args,
@Nullable MediaController.ProgressListener progressListener
)
Sends a custom command to the session for the given media item.
A controller can request progress updates by passing in a non-null ProgressListener. Whether or not the session sends progress updates depends on the implementation of the session callback that responds to the given SessionCommand.
Calling this method is equivalent to calling sendCustomCommand and including the media ID in the argument bundle with key EXTRA_KEY_MEDIA_ID.
A command is not accepted if it is not a custom command or the command is not in the list of available session commands.
Interoperability: When sending a custom command to
android.support.v4.media.session.MediaSessionCompat, resultCode will always be RESULT_SUCCESS because the session has no way to send a result back from onCustomAction.
| Parameters | |
|---|---|
SessionCommand command |
The custom command. |
MediaItem mediaItem |
The media item for which the command is sent. |
Bundle args |
The additional arguments. May be empty. |
@Nullable MediaController.ProgressListener progressListener |
A |
| Returns | |
|---|---|
ListenableFuture<SessionResult> |
A |
setAudioAttributes
public final void setAudioAttributes(
AudioAttributes audioAttributes,
boolean handleAudioFocus
)
Sets the attributes for audio playback, used by the underlying audio track. If not set, the default audio attributes will be used. They are suitable for general media playback.
Setting the audio attributes during playback may introduce a short gap in audio output as the audio track is recreated. A new audio session id will also be generated.
If tunneling is enabled by the track selector, the specified audio attributes will be ignored, but they will take effect if audio is later played without tunneling.
If audio focus should be handled, the usage must be USAGE_MEDIA or USAGE_GAME. Other usages will throw an IllegalArgumentException.
This method must only be called if COMMAND_SET_AUDIO_ATTRIBUTES is available.
| Parameters | |
|---|---|
AudioAttributes audioAttributes |
The attributes to use for audio playback. |
boolean handleAudioFocus |
True if the player should handle audio focus, false otherwise. |
setDeviceMuted
public final void setDeviceMuted(boolean muted, @C.VolumeFlags int flags)
Sets the mute state of the device.
Note that this method affects the device volume. To mute just the current stream, use
setVolume(0) instead.
This method must only be called if COMMAND_ADJUST_DEVICE_VOLUME_WITH_FLAGS is available.
| Parameters | |
|---|---|
boolean muted |
Whether to set the device to be muted or not |
@C.VolumeFlags int flags |
Either 0 or a bitwise combination of one or more |
setDeviceVolume
public final void setDeviceVolume(@IntRange(from = 0) int volume, @C.VolumeFlags int flags)
Sets the volume of the device with volume flags.
Note that this method affects the device volume. To change the volume of the current stream only, use setVolume.
This method must only be called if COMMAND_SET_DEVICE_VOLUME_WITH_FLAGS is available.
| Parameters | |
|---|---|
@IntRange(from = 0) int volume |
The volume to set. |
@C.VolumeFlags int flags |
Either 0 or a bitwise combination of one or more |
setMediaItem
public final void setMediaItem(MediaItem mediaItem)
Clears the playlist, adds the specified MediaItem and resets the position to the default position.
To replace a media item (possibly seamlessly) without clearing the playlist, use replaceMediaItem.
This method must only be called if COMMAND_SET_MEDIA_ITEM is available.
setMediaItem
public final void setMediaItem(MediaItem mediaItem, boolean resetPosition)
Clears the playlist and adds the specified MediaItem.
To replace a media item (possibly seamlessly) without clearing the playlist, use replaceMediaItem.
This method must only be called if COMMAND_SET_MEDIA_ITEM is available.
| Parameters | |
|---|---|
MediaItem mediaItem |
The new |
boolean resetPosition |
Whether the playback position should be reset to the default position. If false, playback will start from the position defined by |
setMediaItem
public final void setMediaItem(MediaItem mediaItem, long startPositionMs)
Clears the playlist and adds the specified MediaItem.
To replace a media item (possibly seamlessly) without clearing the playlist, use replaceMediaItem.
This method must only be called if COMMAND_SET_MEDIA_ITEM is available.
| Parameters | |
|---|---|
MediaItem mediaItem |
The new |
long startPositionMs |
The position in milliseconds to start playback from. If |
setMediaItems
public final void setMediaItems(List<MediaItem> mediaItems)
Clears the playlist, adds the specified media items and resets the position to the default position.
To replace a span of media items (possibly seamlessly) without clearing the playlist, use replaceMediaItems.
This method must only be called if COMMAND_CHANGE_MEDIA_ITEMS is available.
| Parameters | |
|---|---|
List<MediaItem> mediaItems |
The new |
setMediaItems
public final void setMediaItems(List<MediaItem> mediaItems, boolean resetPosition)
Clears the playlist and adds the specified media items.
To replace a span of media items (possibly seamlessly) without clearing the playlist, use replaceMediaItems.
This method must only be called if COMMAND_CHANGE_MEDIA_ITEMS is available.
| Parameters | |
|---|---|
List<MediaItem> mediaItems |
The new |
boolean resetPosition |
Whether the playback position should be reset to the default position in the first |
setMediaItems
public final void setMediaItems(
List<MediaItem> mediaItems,
int startIndex,
long startPositionMs
)
Clears the playlist and adds the specified media items.
To replace a span of media items (possibly seamlessly) without clearing the playlist, use replaceMediaItems.
This method must only be called if COMMAND_CHANGE_MEDIA_ITEMS is available.
| Parameters | |
|---|---|
List<MediaItem> mediaItems |
The new |
int startIndex |
The |
long startPositionMs |
The position in milliseconds to start playback from. If |
| Throws | |
|---|---|
androidx.media3.common.IllegalSeekPositionException |
If the provided |
setPlayWhenReady
public final void setPlayWhenReady(boolean playWhenReady)
Sets whether playback should proceed when getPlaybackState == STATE_READY.
If the player is already in the ready state then this method pauses and resumes playback.
This method must only be called if COMMAND_PLAY_PAUSE is available.
| Parameters | |
|---|---|
boolean playWhenReady |
Whether playback should proceed when ready. |
setPlaybackParameters
public final void setPlaybackParameters(PlaybackParameters playbackParameters)
Attempts to set the playback parameters. Passing DEFAULT resets the player to the default, which means there is no speed or pitch adjustment.
Playback parameters changes may cause the player to buffer. onPlaybackParametersChanged will be called whenever the currently active playback parameters change.
This method must only be called if COMMAND_SET_SPEED_AND_PITCH is available.
| Parameters | |
|---|---|
PlaybackParameters playbackParameters |
The playback parameters. |
setPlaybackSpeed
public final void setPlaybackSpeed(float speed)
Changes the rate at which playback occurs. The pitch is not changed.
This is equivalent to
setPlaybackParameters(getPlaybackParameters().withSpeed(speed)).
This method must only be called if COMMAND_SET_SPEED_AND_PITCH is available.
| Parameters | |
|---|---|
float speed |
The linear factor by which playback will be sped up. Must be higher than 0. 1 is normal speed, 2 is twice as fast, 0.5 is half normal speed. |
setPlaylistMetadata
public final void setPlaylistMetadata(MediaMetadata playlistMetadata)
Sets the playlist MediaMetadata.
This method must only be called if COMMAND_SET_PLAYLIST_METADATA is available.
setRating
public final ListenableFuture<SessionResult> setRating(Rating rating)
Requests that the connected MediaSession rates the current media item. This will cause the rating to be set for the current user. The rating style must follow the user rating style from the session. You can get the rating style from the session through the userRating.
If the user rating was null, the media item does not accept setting user rating.
| Parameters | |
|---|---|
Rating rating |
The rating to set. |
| Returns | |
|---|---|
ListenableFuture<SessionResult> |
A |
setRating
public final ListenableFuture<SessionResult> setRating(String mediaId, Rating rating)
Requests that the connected MediaSession rates the media. This will cause the rating to be set for the current user. The rating style must follow the user rating style from the session. You can get the rating style from the session through the userRating.
If the user rating was null, the media item does not accept setting user rating.
| Returns | |
|---|---|
ListenableFuture<SessionResult> |
A |
setRepeatMode
public final void setRepeatMode(@Player.RepeatMode int repeatMode)
Sets the RepeatMode to be used for playback.
This method must only be called if COMMAND_SET_REPEAT_MODE is available.
| Parameters | |
|---|---|
@Player.RepeatMode int repeatMode |
The repeat mode. |
setShuffleModeEnabled
public final void setShuffleModeEnabled(boolean shuffleModeEnabled)
Sets whether shuffling of media items is enabled.
This method must only be called if COMMAND_SET_SHUFFLE_MODE is available.
| Parameters | |
|---|---|
boolean shuffleModeEnabled |
Whether shuffling is enabled. |
setTrackSelectionParameters
public final void setTrackSelectionParameters(TrackSelectionParameters parameters)
Sets the parameters constraining the track selection.
Unsupported parameters will be silently ignored.
Use getTrackSelectionParameters to retrieve the current parameters. For example, the following snippet restricts video to SD whilst keep other track selection parameters unchanged:
player.setTrackSelectionParameters(
player.getTrackSelectionParameters()
.buildUpon()
.setMaxVideoSizeSd()
.build())This method must only be called if COMMAND_SET_TRACK_SELECTION_PARAMETERS is available.
setVideoSurface
public final void setVideoSurface(@Nullable Surface surface)
Sets the Surface onto which video will be rendered. The caller is responsible for tracking the lifecycle of the surface, and must clear the surface by calling
setVideoSurface(null) if the surface is destroyed.
If the surface is held by a SurfaceView, TextureView or SurfaceHolder then it's recommended to use setVideoSurfaceView, setVideoTextureView or setVideoSurfaceHolder rather than this method, since passing the holder allows the player to track the lifecycle of the surface automatically.
This method must only be called if COMMAND_SET_VIDEO_SURFACE is available.
setVideoSurfaceHolder
public final void setVideoSurfaceHolder(@Nullable SurfaceHolder surfaceHolder)
Sets the SurfaceHolder that holds the Surface onto which video will be rendered. The player will track the lifecycle of the surface automatically.
The thread that calls the SurfaceHolder.Callback methods must be the thread associated with getApplicationLooper.
This method must only be called if COMMAND_SET_VIDEO_SURFACE is available.
| Parameters | |
|---|---|
@Nullable SurfaceHolder surfaceHolder |
The surface holder. |
setVideoSurfaceView
public final void setVideoSurfaceView(@Nullable SurfaceView surfaceView)
Sets the SurfaceView onto which video will be rendered. The player will track the lifecycle of the surface automatically.
The thread that calls the SurfaceHolder.Callback methods must be the thread associated with getApplicationLooper.
This method must only be called if COMMAND_SET_VIDEO_SURFACE is available.
| Parameters | |
|---|---|
@Nullable SurfaceView surfaceView |
The surface view. |
setVideoTextureView
public final void setVideoTextureView(@Nullable TextureView textureView)
Sets the TextureView onto which video will be rendered. The player will track the lifecycle of the surface automatically.
Consider using SurfaceView via setVideoSurfaceView instead of TextureView. SurfaceView generally causes lower battery consumption, and has better handling for HDR and secure content. See Choosing a surface type for more information.
The thread that calls the TextureView.SurfaceTextureListener methods must be the thread associated with getApplicationLooper.
This method must only be called if COMMAND_SET_VIDEO_SURFACE is available.
| Parameters | |
|---|---|
@Nullable TextureView textureView |
The texture view. |
setVolume
public final void setVolume(@FloatRange(from = 0, to = 1) float volume)
Sets the audio volume, valid values are between 0 (silence) and 1 (unity gain, signal unchanged), inclusive.
This method must only be called if COMMAND_SET_VOLUME is available.
| Parameters | |
|---|---|
@FloatRange(from = 0, to = 1) float volume |
Linear output gain to apply to all audio channels. |
stop
public final void stop()
Stops playback without resetting the playlist. Use pause rather than this method if the intention is to pause playback.
Calling this method will cause the playback state to transition to STATE_IDLE and the player will release the loaded media and resources required for playback. The player instance can still be used by calling prepare again, and release must still be called on the player if it's no longer required.
Calling this method does not clear the playlist, reset the playback position or the playback error.
This method must only be called if COMMAND_STOP is available.
unmute
public final void unmute()
If the audio volume is 0, sets the audio volume to a non-zero value decided by the Player to be the most appropriate.
This method must only be called if COMMAND_SET_VOLUME is available.