Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android MediaPlayer streaming stops on network change

I am streaming audio using MediaPlayer on Android.

When the device moves from Wi-Fi to the cell network or vice-versa, the MediaPlayer stops playback.

Typically there are a few seconds-worth of audio in the buffer, so playback does not cease immediately.

Ideally I would like to pick up the stream for uninterrupted playback, but I cannot see how to do it.

I am working with both mp3 files hosted on the server and a live broadcast stream.

like image 370
lightversusdark Avatar asked Jul 29 '12 22:07

lightversusdark


2 Answers

From a servers point of view, changing network mode from WiFi to 3G (visa versa), will look like a brand new connection from a separate IP's (client).

If the server that you are downloading from does not support tracking the stream (e.g number of seconds, sequence, byte) (unlike media-servers),It will have to start serving your mp3 from 0 byte again.

If your URL is pointing to a MP3 file located at a standard HTTP server, your situation will be what to expect. You should look into using a Media streaming server, so you could resume downloading/streaming at your choice. When you receive the intent that the connection is lost/resume, you could point your mediaplayer to the new URL with file-position in the URL (e.g seconds=19, bytes=57365).

Not sure if this helps you, but it explains a bit whats going on "behind the scenes".

like image 112
Vidar Vestnes Avatar answered Nov 14 '22 23:11

Vidar Vestnes


Try setting your setOnCompletionListener and setOnErrorListener. In on complete with a live stream you can just call prepareAsync() again and this will kick off the stream again. There is no graceful way of doing this really unless you write your own media framework.

You can also listen in you onError() for the MEDIA_ERROR_SERVER_DIED you can then fire off the prepareAsync() again.

You'll find that the MediaPlayer will either Error or Complete. If you handle both these callbacks the very least you can do is restart the stream on change of network, as for smooth playback.. that would require custom mediaframework as the android one is pretty shoddy.

like image 31
Chris.Jenkins Avatar answered Nov 14 '22 21:11

Chris.Jenkins