1. 程式人生 > >android官方API之MediaPlayer

android官方API之MediaPlayer

來源:https://developer.android.com/reference/android/media/MediaPlayer

MediaPlayer

public class MediaPlayer 
extends Object implements VolumeAutomationAudioRouting

java.lang.Object
   ↳ android.media.MediaPlayer

 


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:

  1. State Diagram
  2. Valid and Invalid States
  3. Permissions
  4. Register informational and error callbacks

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.

MediaPlayer State diagram

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 reset() is called, it is in the Idle state; and afterrelease() 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 
      reset()
       is called. It is a programming error to invoke methods such as getCurrentPosition()getDuration()getVideoHeight()getVideoWidth()setAudioAttributes(AudioAttributes)setLooping(boolean)setVolume(float, float)pause()start()stop()seekTo(long, int)prepare() or 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 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 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 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 Preparedstate 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 setOnErrorListener(android.media.MediaPlayer.OnErrorListener).
    • 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, 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 prepare(),prepareAsync(), or one of the overloaded setDataSource methods in an invalid state.
  • Calling setDataSource(FileDescriptor), or setDataSource(String), or setDataSource(Context, Uri), orsetDataSource(FileDescriptor, long, long), or 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 prepare() (synchronous) which transfers the object to the Prepared state once the method call returns, or a call to prepareAsync() (asynchronous) which first transfers the object to the Preparing state after the call returns (which occurs almost right away) while the internal player engine continues working on the rest of preparation work until the preparation work completes. When the preparation completes or when 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 setOnPreparedListener(android.media.MediaPlayer.OnPreparedListener).
    • 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 prepare() or 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, start() must be called. After start() returns successfully, the MediaPlayer object is in the Started state. 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 setOnBufferingUpdateListener(OnBufferingUpdateListener). This callback allows applications to keep track of the buffering status while streaming audio/video.
    • Calling 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 pause(). When the call to 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 isPlaying(), and it can be a number of seconds in the case of streamed content.
    • Calling 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 start() returns, the paused MediaPlayer object goes back to the Started state.
    • Calling pause() has no effect on a MediaPlayer object that is already in the Paused state.
  • Calling stop() stops playback and causes a MediaPlayer in the StartedPausedPrepared or PlaybackCompletedstate to enter the Stopped state.
    • Once in the Stopped state, playback cannot be started until prepare() or prepareAsync() are called to set the MediaPlayer object to the Prepared state again.
    • Calling 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 seekTo(long, int).
    • Although the asynchronuous seekTo(long, int) call returns right away, 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 viasetOnSeekCompleteListener(OnSeekCompleteListener).
    • Please note that seekTo(long, int) can also be called in the other states, such as PreparedPaused and PlaybackCompleted state. When seekTo(long, int) is called in those states, one video frame will be displayed if the stream has video and the requested position is valid.
    • Furthermore, the actual current playback position can be retrieved with a call to getCurrentPosition(), which is helpful for applications such as a Music player that need to keep track of the playback progress.
  • When the playback reaches the end of stream, the playback completes.
    • If the looping mode was being set to truewith setLooping(boolean), 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 setOnCompletionListener(OnCompletionListener). The invoke of the callback signals that the object is now in the PlaybackCompleted state.
    • While in the PlaybackCompleted state, calling start() can restart the playback from the beginning of the audio/video source.

    Valid and invalid states

    Method Name

     

    Valid States

     

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

     

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

     

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

     

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

     

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

     

    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 release(), the object is no longer available.

     

    reset

     

    {Idle, Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted, Error}

     

    {}

     

    After 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 Errorstate.

     

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

     

    {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 Errorstate.

     

    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.

     

    setPlaybackParams

     

    {Initialized, Prepared, Started, Paused, PlaybackCompleted, Error}

     

    {Idle, Stopped}

     

    This method will change state in some cases, depending on when it's called.

     

    setScreenOnWhilePlaying any

     

    {}

     

    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 <uses-permission> element.

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

    Callbacks

    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 tosetOnPreparedListener(OnPreparedListener)setOnPreparedListener,setOnVideoSizeChangedListener(OnVideoSizeChangedListener)setOnVideoSizeChangedListener,setOnSeekCompleteListener(OnSeekCompleteListener)setOnSeekCompleteListener,setOnCompletionListener(OnCompletionListener)setOnCompletionListener,setOnBufferingUpdateListener(OnBufferingUpdateListener)setOnBufferingUpdateListener,setOnInfoListener(OnInfoListener)setOnInfoListener,setOnErrorListener(OnErrorListener)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).

    Summary

    Nested classes

    class MediaPlayer.DrmInfo

    Encapsulates the DRM properties of the source. 

    class MediaPlayer.MetricsConstants

     

    class MediaPlayer.NoDrmSchemeException

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

    interface MediaPlayer.OnBufferingUpdateListener

    Interface definition of a callback to be invoked indicating buffering status of a media resource being streamed over the network. 

    interface MediaPlayer.OnCompletionListener

    Interface definition for a callback to be invoked when playback of a media source has completed. 

    interface MediaPlayer.OnDrmConfigHelper

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

    interface MediaPlayer.OnDrmInfoListener

    Interface definition of a callback to be invoked when the DRM info becomes available  

    interface MediaPlayer.OnDrmPreparedListener

    Interface definition of a callback to notify the app when the DRM is ready for key request/response  

    interface MediaPlayer.OnErrorListener

    Interface definition of a callback to be invoked when there has been an error during an asynchronous operation (other errors will throw exceptions at method call time). 

    interface MediaPlayer.OnInfoListener

    Interface definition of a callback to be invoked to communicate some info and/or warning about the media or its playback. 

    interface MediaPlayer.OnMediaTimeDiscontinuityListener

    Interface definition of a callback to be invoked when discontinuity in the normal progression of the media time is detected. 

    interface MediaPlayer.OnPreparedListener

    Interface definition for a callback to be invoked when the media source is ready for playback. 

    interface MediaPlayer.OnSeekCompleteListener

    Interface definition of a callback to be invoked indicating the completion of a seek operation. 

    interface MediaPlayer.OnSubtitleDataListener

    Interface definition of a callback to be invoked when a player subtitle track has new subtitle data available. 

    interface MediaPlayer.OnTimedMetaDataAvailableListener

    Interface definition of a callback to be invoked when a track has timed metadata available. 

    interface MediaPlayer.OnTimedTextListener

    Interface definition of a callback to be invoked when a timed text is available for display. 

    interface MediaPlayer.OnVideoSizeChangedListener

    Interface definition of a callback to be invoked when the video size is first known or updated  

    class MediaPlayer.ProvisioningNetworkErrorException

    Thrown when the device requires DRM provisioning but the provisioning attempt has failed due to a network error (Internet reachability, timeout, etc.). 

    class MediaPlayer.ProvisioningServerErrorException

    Thrown when the device requires DRM provisioning but the provisioning attempt has failed due to the provisioning server denying the request. 

    class MediaPlayer.TrackInfo

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

    Constants

    int MEDIA_ERROR_IO

    File or network related operation errors.

    int MEDIA_ERROR_MALFORMED

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

    int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK

    The video is streamed and its container is not valid for progressive playback i.e the video's index (e.g moov atom) is not at the start of the file.

    int MEDIA_ERROR_SERVER_DIED

    Media server died.

    int MEDIA_ERROR_TIMED_OUT

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

    int MEDIA_ERROR_UNKNOWN

    Unspecified media player error.

    int MEDIA_ERROR_UNSUPPORTED

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

    int MEDIA_INFO_AUDIO_NOT_PLAYING

    Informs that audio is not playing.

    int MEDIA_INFO_BAD_INTERLEAVING

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

    int MEDIA_INFO_BUFFERING_END

    MediaPlayer is resuming playback after filling buffers.

    int MEDIA_INFO_BUFFERING_START

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

    int MEDIA_INFO_METADATA_UPDATE

    A new set of metadata is available.

    int MEDIA_INFO_NOT_SEEKABLE

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

    int MEDIA_INFO_STARTED_AS_NEXT

    The player was started because it was used as the next player for another player, which just completed playback.

    int MEDIA_INFO_SUBTITLE_TIMED_OUT

    Reading the subtitle track takes too long.

    int MEDIA_INFO_UNKNOWN

    Unspecified media player info.

    int MEDIA_INFO_UNSUPPORTED_SUBTITLE

    Subtitle track was not supported by the media framework.

    int MEDIA_INFO_VIDEO_NOT_PLAYING

    Informs that video is not playing.

    int MEDIA_INFO_VIDEO_RENDERING_START

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

    int MEDIA_INFO_VIDEO_TRACK_LAGGING

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

    String MEDIA_MIMETYPE_TEXT_SUBRIP

    This constant was deprecated in API level 28. use MediaFormat.MIMETYPE_TEXT_SUBRIP

    int PREPARE_DRM_STATUS_PREPARATION_ERROR

    The DRM preparation has failed .

    int PREPARE_DRM_STATUS_PROVISIONING_NETWORK_ERROR

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

    int PREPARE_DRM_STATUS_PROVISIONING_SERVER_ERROR

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

    int PREPARE_DRM_STATUS_SUCCESS

    The status codes for MediaPlayer.OnDrmPreparedListener.onDrmPrepared(MediaPlayer, int)listener.

    int SEEK_CLOSEST

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

    int SEEK_CLOSEST_SYNC

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

    int SEEK_NEXT_SYNC

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

    int SEEK_PREVIOUS_SYNC

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

    int VIDEO_SCALING_MODE_SCALE_TO_FIT

    Specifies a video scaling mode.

    int VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING

    Specifies a video scaling mode.

    Fields

    protectedAudioAttributes mAttributes

     

    protected float mAuxEffectSendLevel

     

    protected float mLeftVolume

     

    protected float mRightVolume

     

    Public constructors

    MediaPlayer()

    Default constructor.

    Public methods

    void addOnRoutingChangedListener(AudioRouting.OnRoutingChangedListenerlistener, Handler handler)

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

    void addTimedTextSource(FileDescriptor fd, String mimeType)

    Adds an external timed text source file (FileDescriptor).

    void addTimedTextSource(String path, String mimeType)

    Adds an external timed text source file.

    void addTimedTextSource(FileDescriptor fd, long offset, long length,String mime)

    Adds an external timed text file (FileDescriptor).

    void addTimedTextSource(Context context, Uri uri, String mimeType)

    Adds an external timed text source file (Uri).

    void attachAuxEffect(int effectId)

    Attaches an auxiliary effect to the player.

    void clearOnMediaTimeDiscontinuityListener()

    Clears the listener previously set withsetOnMediaTimeDiscontinuityListener(OnMediaTimeDiscontinuityListener)or setOnMediaTimeDiscontinuityListener(OnMediaTimeDiscontinuityListener, Handler)

    void clearOnSubtitleDataListener()

    Clears the listener previously set withsetOnSubtitleDataListener(OnSubtitleDataListener) orsetOnSubtitleDataListener(OnSubtitleDataListener, Handler).

    static MediaPlayer create(Context context, Uri uri, SurfaceHolder holder,AudioAttributes audioAttributes, int audioSessionId)

    Same factory method as create(Context, Uri, SurfaceHolder) but that lets you specify the audio attributes and session ID to be used by the new MediaPlayer instance.

    static MediaPlayer create(Context context, int resid, AudioAttributes audioAttributes,int audioSessionId)

    Same factory