sandalone sandalone - 3 months ago 14
Android Question

Why MediaPlayer prepare() is not to be used with streams?

The docs for

MediaStream
's method
prepareAsync()
says:


Prepares the player for playback, asynchronously. After setting the
datasource and the display surface, you need to either call prepare()
or prepareAsync(). For streams, you should call prepareAsync(),
which returns immediately
, rather than blocking until enough data
has been buffered.


What bad can go wrong if we use
prepare()
for playing streams? I've been using
prepare()
and I never got into any troubles.

On contrary, in my own case, when I use 'prepareAsync()', the stream does NOT start ever. When I use 'prepare()' the stream starts after buffering period (1s-2s) and plays well. Why is this happening with async method? Is the form for async prepare the same as for
prepare()
?

mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setDataSource(STREAM_URL);
mPlayer.prepareAsync();
mPlayer.start();

Answer

Doing complex operations in the UI thread is a bad practice. It can block your UI for a long time and Android may kill your app. In this case, the prepare() method can take a lot of time due to decoding and fetching data.

You should call the prepareAsync() method while listening the OnPrepared event. When the event is triggered you should notify your UI and start the player.

mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setDataSource(STREAM_URL);
mplayer.setOnPreparedListener(/*your listener here*/)
mPlayer.prepareAsync();