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

前端 未结 2 1950
深忆病人
深忆病人 2021-01-11 14:55

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

相关标签:
2条回答
  • 2021-01-11 15:22

    The difference between those methods is basically in what thread they're executed.

    Prepare runs in the thread you call it (most frequently UI thread) and thus if it takes long time (buffering video from the Internet and such) it will block your UI thread and a user might get ANR.

    PrepareAsync runs in a background thread and thus UI thread is not blocked as it returns almost immediately. But the player is not prepared so you want to set onPreparedListener in order to know when the MediaPlayer is ready to be used.

    0 讨论(0)
  • 2021-01-11 15:40

    prepare() method is generally used when we want to play our media file synchronously. prepareAsync() is generally used when we want to play asynchronously.

    for eg:

    mediaplayer.prepare()
    

    It is used to play the file from local media resources.

    mediaplayer.prepareAsync() is generally used for playing the live data over stream. It allows to play without blocking the main thread. If we use prepare() for live data streaming it eventually crashes because the data is received in streams. Basically what prepare() does it first load all the data and then it play. Thus it allows to play the media file synchronously. And prepareAsync() play the data whatever it has in its buffer.

    Here is the final Quotes

    here 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 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 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).

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

    In your case it must be prepare() method

    Check prepareAsync() and prepare() refer the docs its clearly stated

    0 讨论(0)
提交回复
热议问题