Android Guides | Samples

Android.Media.MediaPlayer Class

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

See Also: MediaPlayer

Syntax

[Android.Runtime.Register("android/media/MediaPlayer", DoNotGenerateAcw=true)]
public class MediaPlayer : Object

Remarks

MediaPlayer class can be used to control playback of audio/video files and streams. An example on how to use the methods in this class can be found in VideoView.

Topics covered here are:

Developer Guides

For more information about how to use MediaPlayer, read the Media Playback developer guide.

State Diagram

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

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

  • When a MediaPlayer object is just created using new or after MediaPlayer.Reset is called, it is in the Idle state; and after MediaPlayer.Release is called, it is in the End state. Between these two states is the life cycle of the MediaPlayer object.
    • There is a subtle but important difference between a newly constructed MediaPlayer object and the MediaPlayer object after MediaPlayer.Reset is called. It is a programming error to invoke methods such as MediaPlayer.CurrentPosition, MediaPlayer.Duration, MediaPlayer.VideoHeight, MediaPlayer.VideoWidth, MediaPlayer.SetAudioStreamType(Stream), MediaPlayer.Looping, MediaPlayer.SetVolume(Single,Single), MediaPlayer.Pause, MediaPlayer.Start, MediaPlayer.Stop, MediaPlayer.SeekTo(Int32), MediaPlayer.Prepare or MediaPlayer.PrepareAsync in the Idle state for both cases. If any of these methods is called right after a MediaPlayer object is constructed, the user supplied callback method OnErrorListener.onError() won't be called by the internal player engine and the object state remains unchanged; but if these methods are called right after MediaPlayer.Reset, the user supplied callback method OnErrorListener.onError() will be invoked by the internal player engine and the object will be transfered to the Error state.
    • It is also recommended that once a MediaPlayer object is no longer being used, call MediaPlayer.Release immediately so that resources used by the internal player engine associated with the MediaPlayer object can be released immediately. Resource may include singleton resources such as hardware acceleration components and failure to call MediaPlayer.Release may cause subsequent instances of MediaPlayer objects to fallback to software implementations or fail altogether. Once the MediaPlayer object is in the End state, it can no longer be used and there is no way to bring it back to any other state.
    • Furthermore, the MediaPlayer objects created using new is in the Idle state, while those created with one of the overloaded convenient create methods are NOT in the Idle state. In fact, the objects are in the Prepared state if the creation using create method is successful.
    • In general, some playback control operation may fail due to various reasons, such as unsupported audio/video format, poorly interleaved audio/video, resolution too high, streaming timeout, and the like. Thus, error reporting and recovery is an important concern under these circumstances. Sometimes, due to programming errors, invoking a playback control operation in an invalid state may also occur. Under all these error conditions, the internal player engine invokes a user supplied OnErrorListener.onError() method if an OnErrorListener has been registered beforehand via MediaPlayer.SetOnErrorListener(.IOnErrorListener).
      • It is important to note that once an error occurs, the MediaPlayer object enters the Error state (except as noted above), even if an error listener has not been registered by the application.
      • In order to reuse a MediaPlayer object that is in the Error state and recover from the error, MediaPlayer.Reset can be called to restore the object to its Idle state.
      • It is good programming practice to have your application register a OnErrorListener to look out for error notifications from the internal player engine.
      • IllegalStateException is thrown to prevent programming errors such as calling MediaPlayer.Prepare, MediaPlayer.PrepareAsync, or one of the overloaded setDataSource methods in an invalid state.
      • Calling MediaPlayer.SetDataSource(FileDescriptor), or MediaPlayer.SetDataSource(String), or MediaPlayer.SetDataSource(Context,Uri), or MediaPlayer.SetDataSource(FileDescriptor,Int64,Int64), or MediaPlayer.SetDataSource(MediaDataSource) transfers a MediaPlayer object in the Idle state to the Initialized state.
        • An IllegalStateException is thrown if setDataSource() is called in any other state.
        • It is good programming practice to always look out for IllegalArgumentException and IOException that may be thrown from the overloaded setDataSource methods.
        • A MediaPlayer object must first enter the Prepared state before playback can be started.
          • There are two ways (synchronous vs. asynchronous) that the Prepared state can be reached: either a call to MediaPlayer.Prepare (synchronous) which transfers the object to the Prepared state once the method call returns, or a call to MediaPlayer.PrepareAsync (asynchronous) which first transfers the object to the Preparing state after the call returns (which occurs almost right way) while the internal player engine continues working on the rest of preparation work until the preparation work completes. When the preparation completes or when MediaPlayer.Prepare call returns, the internal player engine then calls a user supplied callback method, onPrepared() of the OnPreparedListener interface, if an OnPreparedListener is registered beforehand via MediaPlayer.SetOnPreparedListener(.IOnPreparedListener).
          • It is important to note that the Preparing state is a transient state, and the behavior of calling any method with side effect while a MediaPlayer object is in the Preparing state is undefined.
          • An IllegalStateException is thrown if MediaPlayer.Prepare or MediaPlayer.PrepareAsync is called in any other state.
          • While in the Prepared state, properties such as audio/sound volume, screenOnWhilePlaying, looping can be adjusted by invoking the corresponding set methods.
          • To start the playback, MediaPlayer.Start must be called. After MediaPlayer.Start returns successfully, the MediaPlayer object is in the Started state. MediaPlayer.IsPlaying can be called to test whether the MediaPlayer object is in the Started state.
            • While in the Started state, the internal player engine calls a user supplied OnBufferingUpdateListener.onBufferingUpdate() callback method if a OnBufferingUpdateListener has been registered beforehand via MediaPlayer.SetOnBufferingUpdateListener(.IOnBufferingUpdateListener). This callback allows applications to keep track of the buffering status while streaming audio/video.
            • Calling MediaPlayer.Start has not effect on a MediaPlayer object that is already in the Started state.
            • Playback can be paused and stopped, and the current playback position can be adjusted. Playback can be paused via MediaPlayer.Pause. When the call to MediaPlayer.Pause returns, the MediaPlayer object enters the Paused state. Note that the transition from the Started state to the Paused state and vice versa happens asynchronously in the player engine. It may take some time before the state is updated in calls to MediaPlayer.IsPlaying, and it can be a number of seconds in the case of streamed content.
              • Calling MediaPlayer.Start to resume playback for a paused MediaPlayer object, and the resumed playback position is the same as where it was paused. When the call to MediaPlayer.Start returns, the paused MediaPlayer object goes back to the Started state.
              • Calling MediaPlayer.Pause has no effect on a MediaPlayer object that is already in the Paused state.
              • Calling MediaPlayer.Stop stops playback and causes a MediaPlayer in the Started, Paused, Prepared or PlaybackCompleted state to enter the Stopped state.
                • Once in the Stopped state, playback cannot be started until MediaPlayer.Prepare or MediaPlayer.PrepareAsync are called to set the MediaPlayer object to the Prepared state again.
                • Calling MediaPlayer.Stop has no effect on a MediaPlayer object that is already in the Stopped state.
                • The playback position can be adjusted with a call to MediaPlayer.SeekTo(Int32).
                  • Although the asynchronuous MediaPlayer.SeekTo(Int32) call returns right way, the actual seek operation may take a while to finish, especially for audio/video being streamed. When the actual seek operation completes, the internal player engine calls a user supplied OnSeekComplete.onSeekComplete() if an OnSeekCompleteListener has been registered beforehand via MediaPlayer.SetOnSeekCompleteListener(.IOnSeekCompleteListener).
                  • Please note that MediaPlayer.SeekTo(Int32) can also be called in the other states, such as Prepared, Paused and PlaybackCompleted state.
                  • Furthermore, the actual current playback position can be retrieved with a call to MediaPlayer.CurrentPosition, which is helpful for applications such as a Music player that need to keep track of the playback progress.
                  • When the playback reaches the end of stream, the playback completes.

                      Valid and invalid states

                      Method Name Valid Sates Invalid States Comments
                      attachAuxEffect {Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted} {Idle, Error} This method must be called after setDataSource. Calling it does not change the object state.
                      getAudioSessionId any {} This method can be called in any state and calling it does not change the object state.
                      getCurrentPosition {Idle, Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted} {Error}Successful invoke of this method in a valid state does not change the state. Calling this method in an invalid state transfers the object to the Error state.
                      getDuration {Prepared, Started, Paused, Stopped, PlaybackCompleted} {Idle, Initialized, Error} Successful invoke of this method in a valid state does not change the state. Calling this method in an invalid state transfers the object to the Error state.
                      getVideoHeight {Idle, Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted}{Error}Successful invoke of this method in a valid state does not change the state. Calling this method in an invalid state transfers the object to the Error state.
                      getVideoWidth {Idle, Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted}{Error}Successful invoke of this method in a valid state does not change the state. Calling this method in an invalid state transfers the object to the Error state.
                      isPlaying {Idle, Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted}{Error}Successful invoke of this method in a valid state does not change the state. Calling this method in an invalid state transfers the object to the Error state.
                      pause {Started, Paused, PlaybackCompleted}{Idle, Initialized, Prepared, Stopped, Error}Successful invoke of this method in a valid state transfers the object to the Paused state. Calling this method in an invalid state transfers the object to the Error state.
                      prepare {Initialized, Stopped} {Idle, Prepared, Started, Paused, PlaybackCompleted, Error} Successful invoke of this method in a valid state transfers the object to the Prepared state. Calling this method in an invalid state throws an IllegalStateException.
                      prepareAsync {Initialized, Stopped} {Idle, Prepared, Started, Paused, PlaybackCompleted, Error} Successful invoke of this method in a valid state transfers the object to the Preparing state. Calling this method in an invalid state throws an IllegalStateException.
                      release any {} After MediaPlayer.Release, the object is no longer available.
                      reset {Idle, Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted, Error}{}After MediaPlayer.Reset, the object is like being just created.
                      seekTo {Prepared, Started, Paused, PlaybackCompleted} {Idle, Initialized, Stopped, Error}Successful invoke of this method in a valid state does not change the state. Calling this method in an invalid state transfers the object to the Error state.
                      setAudioAttributes {Idle, Initialized, Stopped, Prepared, Started, Paused, PlaybackCompleted}{Error}Successful invoke of this method does not change the state. In order for the target audio attributes type to become effective, this method must be called before prepare() or prepareAsync().
                      setAudioSessionId {Idle} {Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted, Error} This method must be called in idle state as the audio session ID must be known before calling setDataSource. Calling it does not change the object state.
                      setAudioStreamType {Idle, Initialized, Stopped, Prepared, Started, Paused, PlaybackCompleted}{Error}Successful invoke of this method does not change the state. In order for the target audio stream type to become effective, this method must be called before prepare() or prepareAsync().
                      setAuxEffectSendLevel any{} Calling this method does not change the object state.
                      setDataSource {Idle} {Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted, Error} Successful invoke of this method in a valid state transfers the object to the Initialized state. Calling this method in an invalid state throws an IllegalStateException.
                      setDisplay any {} This method can be called in any state and calling it does not change the object state.
                      setSurface any {} This method can be called in any state and calling it does not change the object state.
                      setVideoScalingMode {Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted} {Idle, Error}Successful invoke of this method does not change the state.
                      setLooping {Idle, Initialized, Stopped, Prepared, Started, Paused, PlaybackCompleted}{Error}Successful invoke of this method in a valid state does not change the state. Calling this method in an invalid state transfers the object to the Error state.
                      isLooping any {} This method can be called in any state and calling it does not change the object state.
                      setOnBufferingUpdateListener any {} This method can be called in any state and calling it does not change the object state.
                      setOnCompletionListener any {} This method can be called in any state and calling it does not change the object state.
                      setOnErrorListener any {} This method can be called in any state and calling it does not change the object state.
                      setOnPreparedListener any {} This method can be called in any state and calling it does not change the object state.
                      setOnSeekCompleteListener any {} This method can be called in any state and calling it does not change the object state.
                      setPlaybackRateany {} This method can be called in any state and calling it does not change the object state.
                      setPlaybackParamsany {} This method can be called in any state and calling it does not change the object state.
                      setScreenOnWhilePlayingany {} This method can be called in any state and calling it does not change the object state.
                      setVolume {Idle, Initialized, Stopped, Prepared, Started, Paused, PlaybackCompleted}{Error}Successful invoke of this method does not change the state.
                      setWakeMode any {} This method can be called in any state and calling it does not change the object state.
                      start {Prepared, Started, Paused, PlaybackCompleted}{Idle, Initialized, Stopped, Error}Successful invoke of this method in a valid state transfers the object to the Started state. Calling this method in an invalid state transfers the object to the Error state.
                      stop {Prepared, Started, Stopped, Paused, PlaybackCompleted}{Idle, Initialized, Error}Successful invoke of this method in a valid state transfers the object to the Stopped state. Calling this method in an invalid state transfers the object to the Error state.
                      getTrackInfo {Prepared, Started, Stopped, Paused, PlaybackCompleted}{Idle, Initialized, Error}Successful invoke of this method does not change the state.
                      addTimedTextSource {Prepared, Started, Stopped, Paused, PlaybackCompleted}{Idle, Initialized, Error}Successful invoke of this method does not change the state.
                      selectTrack {Prepared, Started, Stopped, Paused, PlaybackCompleted}{Idle, Initialized, Error}Successful invoke of this method does not change the state.
                      deselectTrack {Prepared, Started, Stopped, Paused, PlaybackCompleted}{Idle, Initialized, Error}Successful invoke of this method does not change the state.

                      Permissions

                      One may need to declare a corresponding WAKE_LOCK permission NoType:android/R$styleable;Href=../../../reference/android/R.styleable.html#AndroidManifestUsesPermission element. This class requires the NoType:android/Manifest$permission;Href=../../../reference/android/Manifest.permission.html#INTERNET permission when used with network-based content.

                      Callbacks

                    • If the looping mode was being set to truewith MediaPlayer.Looping, the MediaPlayer object shall remain in the Started state.
                    • If the looping mode was set to false , the player engine calls a user supplied callback method, OnCompletion.onCompletion(), if a OnCompletionListener is registered beforehand via MediaPlayer.SetOnCompletionListener(.IOnCompletionListener). The invoke of the callback signals that the object is now in the PlaybackCompleted state.
                    • While in the PlaybackCompleted state, calling MediaPlayer.Start can restart the playback from the beginning of the audio/video source.

                    Applications may want to register for informational and error events in order to be informed of some internal state update and possible runtime errors during playback or streaming. Registration for these events is done by properly setting the appropriate listeners (via calls to MediaPlayer.SetOnPreparedListener(.IOnPreparedListener)setOnPreparedListener, MediaPlayer.SetOnVideoSizeChangedListener(.IOnVideoSizeChangedListener)setOnVideoSizeChangedListener, MediaPlayer.SetOnSeekCompleteListener(.IOnSeekCompleteListener)setOnSeekCompleteListener, MediaPlayer.SetOnCompletionListener(.IOnCompletionListener)setOnCompletionListener, MediaPlayer.SetOnBufferingUpdateListener(.IOnBufferingUpdateListener)setOnBufferingUpdateListener, MediaPlayer.SetOnInfoListener(.IOnInfoListener)setOnInfoListener, MediaPlayer.SetOnErrorListener(.IOnErrorListener)setOnErrorListener, etc). In order to receive the respective callback associated with these listeners, applications are required to create MediaPlayer objects on a thread with its own Looper running (main UI thread by default has a Looper running).

                    [Android Documentation]

                    Requirements

                    Namespace: Android.Media
                    Assembly: Mono.Android (in Mono.Android.dll)
                    Assembly Versions: 0.0.0.0
                    Since: Added in API level 1

                    The members of Android.Media.MediaPlayer are listed below.

                    See Also: Object

                    Public Constructors

                    Default constructor.

                    Protected Constructors

                    A constructor used when creating managed representations of JNI objects; called by the runtime.

                    Public Fields

                    const
                    MediaErrorIoInt32 (-1004).
                    const
                    MediaErrorMalformedInt32 (-1007).
                    const
                    MediaErrorTimedOutInt32 (-110).
                    const
                    MediaErrorUnsupportedInt32 (-1010).
                    const
                    MediaMimetypeTextSubripString. MIME type for SubRip (SRT) container.
                    const
                    VideoScalingModeScaleToFitMediaPlayerVideoScalingModeNotInUse (1). Specifies a video scaling mode.
                    const
                    VideoScalingModeScaleToFitWithCroppingMediaPlayerVideoScalingModeNotInUse (2). Specifies a video scaling mode.

                    Public Properties

                    AudioSessionIdInt32. Returns the audio session ID.
                    [read-only]
                    CurrentPositionInt32. Gets the current playback position.
                    [read-only]
                    DurationInt32. Gets the duration of the file.
                    [read-only]
                    IsPlayingBoolean. Checks whether the MediaPlayer is playing.
                    LoopingBoolean. Checks whether the MediaPlayer is looping or non-looping.
                    [read-only]
                    VideoHeightInt32. Returns the height of the video.
                    [read-only]
                    VideoWidthInt32. Returns the width of the video.

                    Protected Properties

                    [read-only]
                    override
                    ThresholdClassIntPtr. This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.
                    [read-only]
                    override
                    ThresholdTypeType. This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

                    Public Methods

                    AddTimedTextSource(FileDescriptor, String)
                    Adds an external timed text source file (FileDescriptor).
                    AddTimedTextSource(String, String)
                    Adds an external timed text source file.
                    AddTimedTextSource(Context, Uri, String)
                    Adds an external timed text source file (Uri).
                    AddTimedTextSource(FileDescriptor, Int64, Int64, String)
                    Adds an external timed text file (FileDescriptor).
                    AttachAuxEffect(Int32)
                    Attaches an auxiliary effect to the player.
                    static
                    Create(Context, Uri) : MediaPlayer
                    Convenience method to create a MediaPlayer for a given Uri.
                    static
                    Create(Context, Int32) : MediaPlayer
                    Convenience method to create a MediaPlayer for a given resource id.
                    static
                    Create(Context, Uri, ISurfaceHolder) : MediaPlayer
                    Convenience method to create a MediaPlayer for a given Uri.
                    static
                    Create(Context, Int32, AudioAttributes, Int32) : MediaPlayer
                    Same factory method as MediaPlayer.Create(Context,Int32) but that lets you specify the audio attributes and session ID to be used by the new MediaPlayer instance.
                    static
                    Create(Context, Uri, ISurfaceHolder, AudioAttributes, Int32) : MediaPlayer
                    Same factory method as MediaPlayer.Create(Context,Uri,Uri) but that lets you specify the audio attributes and session ID to be used by the new MediaPlayer instance.
                    DeselectTrack(Int32)
                    Deselect a track.
                    GetSelectedTrack(MediaTrackType) : Int32
                    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 MediaPlayer.GetTrackInfo, and can be used in calls to MediaPlayer.SelectTrack(Int32) or MediaPlayer.DeselectTrack(Int32).
                    GetTrackInfo() : MediaPlayer+TrackInfo[]
                    Returns an array of track information.
                    Pause()
                    Pauses playback.
                    Prepare()
                    Prepares the player for playback, synchronously.
                    PrepareAsync()
                    Prepares the player for playback, asynchronously.
                    Release()
                    Releases resources associated with this MediaPlayer object.
                    Reset()
                    Resets the MediaPlayer to its uninitialized state.
                    SeekTo(Int32)
                    Seeks to specified time position.
                    SelectTrack(Int32)
                    Selects a track.
                    SetAudioAttributes(AudioAttributes)
                    Sets the audio attributes for this MediaPlayer.
                    SetAudioStreamType(Stream)
                    Sets the audio stream type for this MediaPlayer.
                    SetAuxEffectSendLevel(Single)
                    Sets the send level of the player to the attached auxiliary effect.
                    SetDataSource(FileDescriptor)
                    Sets the data source (FileDescriptor) to use.
                    SetDataSource(String)
                    Sets the data source (file-path or http/rtsp URL) to use.
                    SetDataSource(Context, Uri)
                    Sets the data source as a content Uri.
                    SetDataSource(Context, Uri, IDictionary<string, string>)
                    SetDataSource(FileDescriptor, Int64, Int64)
                    Sets the data source (FileDescriptor) to use.
                    SetDataSourceAsync(FileDescriptor) : Task
                    SetDataSourceAsync(String) : Task
                    SetDataSourceAsync(Context, Uri) : Task
                    SetDataSourceAsync(Context, Uri, IDictionary<string, string>) : Task
                    SetDataSourceAsync(FileDescriptor, Int64, Int64) : Task
                    SetDisplay(ISurfaceHolder)
                    Sets the ISurfaceHolder to use for displaying the video portion of the media.
                    SetNextMediaPlayer(MediaPlayer)
                    Set the MediaPlayer to start when this MediaPlayer finishes playback (i.e. reaches the end of the stream).
                    SetOnBufferingUpdateListener(MediaPlayer+IOnBufferingUpdateListener)
                    Register a callback to be invoked when the status of a network stream's buffer has changed.
                    SetOnCompletionListener(MediaPlayer+IOnCompletionListener)
                    Register a callback to be invoked when the end of a media source has been reached during playback.
                    SetOnErrorListener(MediaPlayer+IOnErrorListener)
                    Register a callback to be invoked when an error has happened during an asynchronous operation.
                    SetOnInfoListener(MediaPlayer+IOnInfoListener)
                    Register a callback to be invoked when an info/warning is available.
                    SetOnPreparedListener(MediaPlayer+IOnPreparedListener)
                    Register a callback to be invoked when the media source is ready for playback.
                    SetOnSeekCompleteListener(MediaPlayer+IOnSeekCompleteListener)
                    Register a callback to be invoked when a seek operation has been completed.
                    SetOnTimedTextListener(MediaPlayer+IOnTimedTextListener)
                    Register a callback to be invoked when a timed text is available for display.
                    SetOnVideoSizeChangedListener(MediaPlayer+IOnVideoSizeChangedListener)
                    Register a callback to be invoked when the video size is known or updated.
                    SetScreenOnWhilePlaying(Boolean)
                    Control whether we should use the attached SurfaceHolder to keep the screen on while video playback is occurring.
                    SetSurface(Surface)
                    Sets the Surface to be used as the sink for the video portion of the media.
                    SetVideoScalingMode(VideoScalingMode)
                    Sets video scaling mode.
                    SetVolume(Single, Single)
                    Sets the volume on this player.
                    SetWakeMode(Context, WakeLockFlags)
                    Set the low-level power management behavior for this MediaPlayer.
                    Start()
                    Starts or resumes playback.
                    Stop()
                    Stops playback after playback has been stopped or paused.

                    Public Events