Android: Media Player difference between PrepareAsync () and Prepare ()

I wanted to implement the basic functions of a media player and was confused between PrepareAsync () and Prepare () method calls. Which one should be used if the audio file is in the source folder.

+5
source share
2 answers

The difference between these methods is mainly in which thread they are executed.

Prepare is executed in the thread that you call (most often in the user interface thread), and thus, if it takes a lot of time (video buffering from the Internet, etc.), it blocks your user interface thread and the user can get ANR .

PrepareAsync runs in the background thread, and thus the UI thread is not blocked, as it returns almost immediately. But the player is not prepared, so you want to install onPreparedListener to know when MediaPlayer ready to use.

+8
source
Method

prepare () is usually used when we want to play a media file synchronously. prepareAsync () is usually used when we want to play asynchronously.

eg:

 mediaplayer.prepare() 

Used to play a file from local media resources.

mediaplayer.prepareAsync () is commonly used to play live data in a stream. It allows you to play without blocking the main stream. If we use prepare() to stream data in real time, it will eventually fail because the data is being received in streams. Basically, that prepare() first loads all the data and then plays it back. Thus, it allows you to play media files synchronously. And prepareAsync() plays the data, all that it has in its buffer.

Here are the final quotes

there are two ways (synchronous or asynchronous) that the prepared state can be achieved: either call to prepare () (synchronous), which transfers the object to the ready state after calling the method, or call prepareAsync () (asynchronous), which first transfers the object to the preparation state after the call is returned (which happens almost correctly), while the player’s internal engine continues to work on the rest of the preparation until the preparatory work is completed. When preparation completes or when prepare (), the player’s internal engine then calls the user the callback method, onPrepared () for the OnPreparedListener interface, if OnPreparedListener is registered in advance setOnPreparedListener (android.media.MediaPlayer.OnPreparedListener).

The main difference is that when we use files, we call prepare (), and when we use threads, we call prepareAsync ().

In your case, this should be the prepare () method

Check prepareAsync () and prepare () in the docs clearly indicated

+8
source

Source: https://habr.com/ru/post/1200920/


All Articles