Example analysis of mediaplayer state machine interface method for Android media development

1、 Introduction to mediaplayer state machine

Legend of Android mediaplayer status:

1. Idle status and end status

Mediaplayer object declaration cycle: the whole life cycle of mediaplayer is from idle to end;

--Life cycle start: enter idle state-- End of life cycle: enter the end state;

Idle and end state transitions:

--Enter idle state: mediaplayer enters idle state just after new mediaplayer() is created or reset() method is called-- Enter the end state: after calling the release() method in the idle state, it will enter the end state;

The difference between the two methods for entering the idle state: getcurrentposition(), getduration(), getvideoheight(), getvideowidth(), setaudiostreamtype (int), setlooping (Boolean), SetVolume (float, float), pause(), start(), stop(), seekto(), prepare(), prepareasync() methods cannot be called in the idle state, which is wrong;

--New mediaplayer() enters the idle state: at this time, the internal engine and state of mediaplayer have not changed. After calling the above method, it cannot be called

Onerrorlistener. Onerror() method;

--Reset() enters idle state: if the above method is called, the internal engine will call back the onerrorlistener. Onerror() method;

Differences between creating and reloading mediaplayer:

--Create mediaplayer: the object created through new mediaplayer() is in idle state-- Overload mediaplayer: the mediaplayer object created by the create () method is in the prepare state;

End status resolution:

--Function of release() method: this method will release resources related to mediaplayer in the playback engine-- Release unique resources: some resources, such as hardware acceleration components and singleton components, are unique resources. If they are not released, subsequent mediaplayer will not operate normally-- Unable to perform state transition: the end state represents the end of the mediaplayer life cycle. This state cannot be converted to other states;

2. Error status

Error state transition: when mediaplayer has some errors, such as format error and high resolution, the player engine will call onerrorlistener. Onerror() method;

--Enter the error state: the client calls the onerrorlistener. Onerror() method to enter the error state-- Leave the error state: if you want to use the mediaplayer in the error state, you can use the reset () method to enter the idle state;

Register listener: register an onerrorlistener listener by programming to obtain the errors occurred in the player engine;

--Registration method: call mediaplayer.setonerrorlistener (onerrorlistener) method to register onerrorlistener;

Some exceptions are thrown: calling a method in an illegal place will throw an IllegalStateException;

3. Initialized status

Initialized state transition: call the setdatasource () method in the idle state, and mediaplayer will migrate to the initialized state-- Note: this method can only be called in the idle state. If this method is called in other states, an IllegalStateException will be reported;

4. Prepared and preparing status

Prepared state transition:

--Migration from the initialized state: call the prepare() method in the initialized state. If the method returns successfully, mediaplayer will enter the prepared state-- Migration from preparing state: call onpreparelistener. Onprepared() method in preparing state to migrate to prepared state;

Preparing state: in the initialized state, call the prepareasync() method to enter the preparing state;

--Operations performed in this state: in the preparing state, the player engine will continue to complete the preparation. When the synchronous version returns or the asynchronous version preparation is completed, the onpreparelistener. Onprepared() method will be called to enter the prepared state;

Throw exception: prepare() and prepareasync() methods can be called only in the initialized method, and IllegalStateException will be reported when calling in other states;

Operations that mediaplayer can perform in the prepared state: mediaplayer can perform operations such as audio and video attributes and loop attributes in this state;

5. Started status

Started state migration: call the start () method in the prepared state, and mediaplayer will migrate to the started state;

--Judge whether mediaplayer is in the started state: call isplaying() method in any state to judge whether mediaplayer is in the started state-- Trace buffer status: in the started status, call the onbufferingupdatelistener. Onbufferingupdate() method to obtain the buffer status of the video and audio stream;

6. Paused status

Paused state migration: call pause() method in the started state, and mediaplayer will enter the paused state;

--State migration time: it takes a certain time to convert the started state to the paused state. This process is asynchronous. After a period of time, the isplaying() state will change-- Return to the started state: call the start () method in the paused state to enter the started state;

7. Stopped status

Stopped state migration: call the stop() method in the prepared, started, paused and playbackcompleted States, and mediaplayer will migrate to the stopped state;

8. Play position adjustment

Seekto() method description: this method is asynchronous. After calling, the player engine needs to perform other operations to complete the jump;

--Operation: the player engine will call back the onseekcomplete. Onseekcomplete() method, which is registered through the setonseekcompletelistener() method-- Seekto() method call status: this method can be called in prepared and playbackcompleted status-- Get playback position: call getcurrentposition() method to get the current playback position and help the player update the progress bar;

9. Playbackcompleted status

Cycle mode on: if the cycle mode is enabled by using setlooping(), mediaplayer will re-enter the started state after playing;

Playbackcompleted state migration: if the loop mode is not set, the oncompletion. Oncompletion() callback method will be called after playback, and mediaplayer will enter the playbackcompleted state;

--Oncompletion registration: call mediaplayer. Setoncompletionlistener() to register the listener-- Method for entering the started state: when in the playbackcompleted state, call the satrt () method to enter the started state;

2、 Mediaplayer interface and constants

1. Mediaplayer interface

(1) Buffer related interface

Interface introduction:

--Interface name: mediaplayer.onbufferingupdatelistener-- Interface function: define a callback interface, which is used to indicate the status when the streaming media buffer status changes;

Introduction to interface method:

--Interface method: public abstract void onbufferingupdate (mediaplayer MP, int percent) -- method function: this method calls back when mediaplayer downloads the buffered video stream through HTTP to change the video buffering state-- Method parameter: MP, the mediaplayer entity object; Percent is the percentage of media streams that have been buffered or played;

(2) Relevant interface after playing

Interface introduction:

--Interface name: mediaplayer.oncompletionlistener-- Interface function: defines the callback method after the streaming media is played in the interface;

Introduction to interface method:

--Interface method: public abstract void oncompletion (mediaplayer MP) -- method function: call back after the media stream is played;

(3) Error related interface

Interface introduction:

--Interface name: mediaplayer.onerrorlistener-- Interface function: define a callback method in this interface. This method will be called back when an error occurs in asynchronous operation. In other cases, an exception will be thrown directly when an error occurs;

Introduction to interface method:

--Interface method: public abstract Boolean onerror (mediaplayer MP, int what, int extra) -- method function: call back the method when an error occurs in asynchronous operation-- Parameter Description: -- A. mediaplayer MP: mediaplayer entity class--- b. Int what: the type of error that occurred, such as media_ ERROR_ Unkonwn (wrong position) or media_ ERROR_ SERVER_ Did (server error)--- c. Int extra: an additional code for a specific error, which is used to locate more detailed information about the error, such as media_ ERROR_ IO (local file or network related error), media_ ERROR_ Malformat (bitstream does not comply with relevant coding standards and file specifications), media_ ERROR_ Unsupported (the framework does not support this function), media_ ERROR_ TIME_ Out (some operations timeout);

--Method execution result: true is returned for successful processing errors and false is returned for processing failures. If the listener for this method is not set, call oncompletionlistener listener directly;

(4) Information related interface

Interface introduction:

--Interface name: mediaplayer.oninfolistener-- Interface function: the interface defines a callback method, which calls back the method when a message or warning occurs during media playback;

Introduction to interface method:

--Interface method:

Public abstract Boolean oninfo (mediaplayer MP, int extra) -- method function: call back when a message or warning occurs-- Parameter Description: -- A. mediaplayer MP: mediaplayer entity object;

---B. int what: type of information or warning, such as media_ INFO_ Unknown, media_ INFO_ VEdio_ TRACK_ Lagging (video too complex, decoding too slow), media_ INFO_ VEdio_ RENDERING_ Start, media_ INFO_ BUFFRING_ Start (pause playback, start buffering more data), media_ INFO_ BUFFERING_ End (buffer enough data to restart playback), media_ INFO_ BAD_ Interleaving, media_ INFO_ NOT_ Seekable, media_ INFO_ MetaDATA_ Update (for a new set of metadata), media_ INFO_ UNSUPPORTED_ Subtitle, media_ INFO_ SUBTITLE_ TIMED_ Out (reading subtitles takes too long)--- c. Int extra: type of information or warning,

--Return value: true will be returned if the information is processed, false will be returned if it is not processed, and the information will be ignored if the listener is not registered;

(5) Prepare to play relevant interfaces

Interface introduction:

--Interface name: mediaplayer.onpreparedlistener-- Interface function: a callback method is defined in the interface, which will call back when it enters the prepared state and starts playing;

Introduction to interface method:

--Interface method:

Public abstract void onprepared (mediaplayer MP) -- method function: this method calls back when it enters the prepared state and starts playing-- Parameter Description: mediaplayer MP, mediaplayer entity object;

(6) Find operation related interfaces

Interface introduction:

--Interface name: mediaplayer.onseekcompletelistener-- Interface function: this interface defines a callback method, which will call back after the search operation is completed;

Introduction to interface method:

--Interface method: public abstract void onseekcomplete (mediaplayer MP) -- method function: call back the method when the lookup operation is completed;

(7) Video size related interface

Interface introduction:

--Interface name: mediaplayer.onvideosizechangedlistener-- Interface function: a callback method is defined in the interface to call back the method when the video size is known or updated for the first time;

Introduction to interface method:

--Interface method:

Public abstract void onvideosizechanged (mediaplayer MP, int width, int height) -- this method is used to call back when the video size is updated. If there is no video, it returns 0-- Parameter analysis: int width video width, int height video height;

3、 Analysis of common methods of mediaplayer

1. Mediaplayer construction method

Note: the mediaplayer created with the create () method directly specifies the media resources, and there is no need to call the prepare () method;

(1) Default construction method

Method name: public mediaplayer();

public MediaPlayer ()

Method introduction: the default construction method. The created mediaplayer automatically enters the idle state. Unlike the create() method, the created mediaplayer automatically enters the prepared state;

--Comparison between the two methods: because the create () method specifies the data source when it is created, there is no need to set the data in the idle state and call the prepare () method;

(2) Specifies the construction method of the URI

Method name: public static mediaplayer create (context, URI);

public static MediaPlayer create (Context context,Uri uri)

Method introduction: create a mediaplayer object according to the given URI. If the creation is successful, the prepare () method will be called automatically. Call it again. After mediaplayer is used, use the release () method, otherwise an error will occur;

Return value: the mediaplayer object is returned if the creation is successful, and null if the creation fails;

Parameter introduction:

--Context: context object of Android-- Uri: URI of the data source;

(3) Specify the resource ID

Method name: public static mediaplayer create (context, int resid);

public static MediaPlayer create (Context context,int resid)

Method introduction: create a mediaplayer object with a given raw resource ID;

Parameter Description: int rest sets the playback source file, which refers to the raw resource ID;

(4) Specify the ID and surfaceview

Method name: public static mediaplayer create (context, URI, surfaceholder);

public static MediaPlayer create (Context context,SurfaceHolder holder)

Method introduction: create a mediaplayer and specify the mediaplayer data source URI and surfaceview objects;

Parameter introduction:

--Context: context object of Android-- Uri: the data source of the specified network media-- Surfaceholder: Specifies the surfaceholder to play the video;

2. Method of obtaining player related properties

(1) Get current location

Method name: public int getcurrentposition();

Method parsing: get the playing position of the current player, and the return value is the number of milliseconds that have been played;

Valid and invalid state of method:

--Valid status: idle, initialized, prepared, stopped, playbackcompleted. Calling this method in the above status will not change the mediaplayer status-- Invalid state: error state. Calling this method in error state will enter error state;

(2) Get file duration

Method name: public int getduration();

Method parsing: get the playing time (MS) of the file. If there is no available time, it will return - 1;

Valid and invalid states of the method: the playing file duration can be obtained only in the non error state after setting the data source;

--Valid state: prepared. Calling this method in the above state will not change the mediaplayer state-- Invalid status: idle, error status, will enter error status;

(3) Get video height and width

Method name: public int getvideoheight(), public int getvideowidth();

Method parsing: returns the height or width of the video. If there are no resources, it will return 0. When the video size changes, you can use mediaplayer.onvideosizechangedlistener to listen to the event;

Valid and invalid states of methods: all States except error;

--Valid status: idle, which will enter the error status;

(4) Check if mediaplayer is looping

Method name: public Boolean islooping();

Method parsing: check whether mediaplayer is playing circularly. If it is true, it returns false;

Valid state and invalid state of method: valid in any state, including error state;

(5) Check if mediaplayer is playing

Method name: public Boolean isplaying();

Method parsing: check whether mediaplayer is playing;

Valid status and invalid status of method: you can check whether mediaplayer is playing in all statuses except error;

--Valid state: idle, it will enter the error state and throw the IllegalStateException;

3. Methods related to state migration

(1) Pause playback

Method name: public void pause();

Method parsing: pause playback. If you want to resume playback, call the start () method;

Valid state and invalid state of the method: only in the started and paused states are valid. Calling the method in the started state enters the paused state, and calling the method in the paused state does not work;

--Valid state: started. Calling this method in the above state will not change the mediaplayer state-- Invalid status: error, idle, playbackcompleted status, throw IllegalStateException;

(2) Sync ready to play

Method name: public void prepare();

Method analysis: This is a synchronous method. After setting the data source and playing vector, call the method or prepareAsync () method to play the normal playback. If the method invocation is successful, it can play normally.

Valid state and invalid state of the method: only in the initialized and stopped states -- valid state: initialized, will enter the error state;

(3) Asynchronous ready to play

Method name: public void prepareasync();

Method function: an asynchronous method to make the player ready;

-- calling time: after the data source and playing vector are set, the method is called; Application: for streaming media, calling this method to return immediately is better than blocking and waiting for enough data to be buffered during playback;

Method's valid and invalid states: only in initialized and stopped states

--Valid status: initialized, it will enter the error status;

(4) Release mediaplayer

Method name: public void release();

Method parsing: release resources related to mediaplayer;

--Call timing: call this method to release resources when the activity played by mediaplayer pauses, stops or destroys;

Valid and invalid states of methods: you can call the release () method in any state;

(5) Reset mediaplayer

Method name: public void reset();

Method parsing: reset the mediaplayer to the idle state. At this time, the data source has not been set. If you want to play media resources, you need to set the data source and call the prepare() method;

Valid and invalid states of methods: you can call the release () method in any state;

4. Set data source related methods

(1) Set local file path

Method name: public void setdatasource (string path);

Method parsing: set a file path or http / RTSP address as the data source;

Parameter resolution: string path, file path of media resource or http / RTSP URL address path;

Valid status and invalid status of method: the data source can be set only in idle status, and errors will be reported in other cases;

--Valid state: idle. Calling this method in the above state will not change the mediaplayer state-- Invalid status: initialized, error status, will enter the error status;

(2) Set file descriptor

Method name: public void setdatasource (filedescriptor FD);

Method parsing: set a file descriptor resource, and the caller should pay attention to closing the file descriptor;

Parameter analysis: filedescriptor SD, file description of UNIX system, equivalent to a file;

Valid status and invalid status of method: the data source can be set only in idle status, and it will enter error status;

(3) Set the data source to intercept only one segment

Method name: public void setdatasource (filedescriptor FD, long offset, long length);

Method parsing: set a file descriptor data source, and the file descriptor file must be queryable;

Parameter resolution:

--Filedescriptor FD: file descriptor-- Long offset: the position where the file starts playing, which refers to the number of bytes-- Long length: the size and number of bytes of the file to be played;

Valid status and invalid status of method: the data source can be set only in idle status, and it will enter error status;

(4) Set URI path

Method name: public void setdatasource (context, URI, URI);

Method introduction: set a URI path as the data source;

Parameter introduction:

--Context: Android context object-- Uri: network media file data source;

Valid status and invalid status of method: the data source can be set only in idle status, and it will enter error status;

5. Relevant methods for setting up listeners

Note: the methods related to the registered listener can be called in any state of mediaplayer;

(1) Register buffer change related listeners

Method name: public void setonbufferingupdatelistener (mediaplayer. Onbufferingupdatelistener listener);

Method function: register a listener to call back after the network buffer data flow changes;

(2) Register playback completion listener

Method name: public void setoncompletionlistener (mediaplayer. Oncompletionlistener listener);

Method function: register a playback event called back after the media resource is played;

(3) Register error listener

Method name: public void setonerrorlistener (mediaplayer. Onerrorlistener listener);

Method parsing: register a listener with error callback during asynchronous operation;

(4) Register event listener

Method name: public void setoninfolistener (mediaplayer. Oninfolistener listener);

Method parsing: register a listener that will call back when there is a message or warning;

(5) Register ready to play listener

Method name: public void setonpreparedlistener (mediaplayer. Onpreparedlistener listener);

Method parsing: register a listener to call back when the media resource is ready to play;

(6) Register search operation listener

Method name: public void setonseekcompletelistener (mediaplayer. Onseekcompletelistener listener);

Method parsing: register a listener called back after the search operation is completed;

(7) Register video size change listener

Method name: public void setonvideosizechangedlistener (mediaplayer. Onvideosizechangedlistener listener);

Method analysis: register a listener to call back when the video size is known or updated;

6. Other settings of mediaplayer

(1) Specifies the audio stream type

Method name: public void setaudiostreamtype (int streamtype);

Method analysis: set the audio stream type for MediaPlayer, and the audio type is defined in AudioManager, which must be called before prepare () or prepareAsync ().

Valid and invalid state of method:

--Valid state: idle. Calling this method in the above state will enter the paused state-- Invalid status: error status, which will enter the error status;

(2) Set playback carrier

Method name: public void setdisplay (surfaceholder SH);

Method analysis: set the carrier surfaceholder of the media player. If you want to play video, you must set this item or any of setsurface(). If you play audio, you cannot set this item. If you play video without setting this item, only sound will be played;

Effective state and invalid state of the method: it is effective in any state and will not change the current running state;

(3) Set loop playback

Method name: public void setlooping (Boolean looping);

Method analysis: set whether the player plays circularly;

Valid and invalid state of method:

--Valid state: idle. Calling this method in the above state will not change the current state-- Invalid status: error status, which will enter the error status;

(4) Set whether to keep the screen

Method name: public void setscreen onwileplaying (Boolean screenon);

Method analysis: set whether to use surfaceholder to keep the screen lit when the video is played;

Valid state and invalid state of method: any state can be called and will not change the current state;

(5) Set power management status

Method name: public void setwakemode (context, int mode);

Method analysis: set the power management status for mediaplayer;

Valid state and invalid state of method: any state can be called and will not change the current state;

summary

The above is an example analysis of the mediaplayer state machine interface method for Android media development introduced by Xiaobian. I hope it will be helpful to you. If you have any questions, please leave me a message and Xiaobian will reply to you in time. Thank you very much for your support for the programming tips website!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>