Android media playback-media playback (2)

Source: Internet
Author: User
Tags thread logic

Use mediaplayer

One of the most important components of a media framework is the mediaplayer class. This class of objects can be obtained, decoded, and played in the smallest step. It supports the following media sources:

1. Local resources;

2. The internal Uniform Resource Identifier (URI), which may be obtained from the content parser;

3. External uri (Stream ).

For the list of media formats supported by Android, see the "media formats supported by Android" document.

Http://developer.android.com/guide/appendix/media-formats.html

The following is an example of how to play a local Native audio resource. The resource is stored in the Res/raw/directory of the application.

Mediaplayer = mediaplayer. Create (context, R. Raw. sound_file_1 );

Mediaplayer. Start (); // No need to call prepare (); Create () does that for you

In this scenario, a "native" resource is a file that the system does not parse in any special way. However, the content of such resources should not be the original audio. It should be a media file that is properly encoded and formatted in a format supported by the resource.

The following is an example of how to use a locally available URI in the system for playback:

Uri myuri =...; // initialize URI here

Mediaplayer = new mediaplayer ();

Mediaplayer. setaudiostreamtype (audiomanager. stream_music );

Mediaplayer. setdatasource (getapplicationcontext (), myuri );

Mediaplayer. Prepare ();

Mediaplayer. Start ();

 

The following is an example of using a remote URL for HTTP stream playback:

String url = "http: // ......"; // your url here

Mediaplayer = new mediaplayer ();

Mediaplayer. setaudiostreamtype (audiomanager. stream_music );

Mediaplayer. setdatasource (URL );

Mediaplayer. Prepare (); // might take long! (For buffering, etc)

Mediaplayer. Start ();

Note: If the URL points to the stream of an online media file, the file must be incrementally downloaded.

Warning when using the setdatasource () method, the illegalargumentexception and ioexception must be caught or passed.

 

Asynchronous preparation

Using mediaplayer is simple in terms of principles, but to integrate it correctly with a typical Android Application, you need to remember several important things. For example, calling the prepare () method may take a long time because it may need to obtain and decode media data. In this case, any method may take a long time to execute, so it should not be called in the UI thread of the application. During execution, the UI may be suspended until the method is returned. This user experience is very bad and can cause an ANR (Application
Not responding) error. Even if you think the resources will be quickly loaded, remember that any response of more than 10 seconds will pause on the UI interface, which will give you the impression of slow application execution.

To avoid the suspension of the UI thread, use another thread to prepare the mediaplayer and send a notification to the main thread when the execution is complete. You can write your own thread logic, but this method of using mediaplayer is very common. Therefore, the Framework provides a convenient way to complete this task by using the prepareasync () method. This method starts the media preparation process in the background and returns immediately. After the media is prepared, the onprepared () method of the mediaplayer. onpreparedlistener configured through the setonpreparedlistener () method is called.

 

Management Status

Another feature of the mediaplayer to remember is that it is State-based. That is to say, mediaplayer has an internal status. You must pay attention to this status when writing your own code, because an operation may only be valid in a specific status. If an operation is performed in an incorrect state, the system throws an exception or causes other undesirable behaviors.

The mediaplayer document shows a complete state chart, which clarifies how to transfer a mediaplayer from one state to another. For example, when a new mediaplayer object is created, it is in the idle state. At this point in time, you should call the setdatasource () method to initialize, followed by the initialized status. You must use the prepare () or prepareasync () method to prepare the media. When the mediaplayer completes preparation, it enters the prepared State, which means that the START () method can be called to play the media. As shown in the figure, the START (), pause (), and seekto () methods are called to switch between the started, paused, and playbackcompleted states. When calling the stop () method, you must note that you cannot call the START () method before preparing the mediaplayer again.

Always remember this status chart when writing code that interacts with a mediaplayer object, because the method to call it in the wrong state is the most common bug.

Release a mediaplayer object

Mediaplayer can digest valuable system resources. Therefore, other measures are always required to ensure that the mediaplayer will not be suspended due to long instantiation. When processing is complete, always call the release () method to ensure that the system resources it occupies are correctly released. For example, if you are using mediaplayer and the activity receives an onstop () call, you must release the mediaplayer object because the activity no longer interacts with the user, therefore, it is meaningless to hold this mediaplayer object (unless you want to play the media in the background ). When the activity is in recovery or restart state, you need to create a new mediaplayer object and prepare it again before resuming playback.

The following is an example of how to release and cancel a mediaplayer object:

Mediaplayer. Release ();

Mediaplayer = NULL;

As an example, you also need to consider the possible problem of forgetting to release the mediaplayer object when the activity is terminated, because a new mediaplayer object is created every time the activity is restarted. As you know, when a user changes the screen direction (or changes the device configuration in another way), the system must restart the activity (default) to handle this change, therefore, when users repeatedly switch between the portrait and landscape screens, all system resources may be quickly consumed, because a new mediaplayer object must be created for each change, the previous version has not been released.

You may think that if the user leaves the activity, the built-in music application will use this behavior when playing the media in the background. In this scenario, a service is required to control the mediaplayer object.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.