Streaming to the Android MediaPlayer
The
HTTP
Server was indeed hosted on the phone itself. It was very simple: just athread
listening on a socket for anHTTP GET
request. When it got theHTTP
request, it would one anew socket
, write back someHTTP
headers and start dumping theMP3
audio data back to thesocket
. ThisHTTP
server didn't do anything else.The
Android Media Player
was playing the music as I was streaming to it. TheMedia Player
behaved very poorly if its playbackbuffer
was emptied while it was playing audio. It was very important for me to make sure myHTTP
server kept writing data into thatsocket
. I moved bytes into the socket in small chunks (10 kB). The headers on myHTTP
response ended up looking like this:// Build response headers StringBuilder sb = new StringBuilder(); sb.append( "HTTP/1.1 200 OK\r\n"); sb.append( "Content-Type: audio/mpeg\r\n"); sb.append( "Connection: close\r\n" ); sb.append( "Accept-Ranges: bytes\r\n" ); sb.append( "Content-Length: " + totalFileSize + "\r\n" ); sb.append( "Content-Disposition: inline; filename=xxxxx.mp3\r\n\r\n");
As long as I kept the pipe stoked, the
Android Media Player
kept consuming it without complaint. Playing audio only required one request and response. It ended up working pretty well.
Related videos on Youtube
Rob Szumlakowski
Updated on July 09, 2022Comments
-
Rob Szumlakowski almost 2 years
I'm trying to write a light-weight
HTTP
server in my app tofeed
dynamically generatedMP3
data to the built-inAndroid
MediaPlayer
. I am not permitted to store my content on theSD card
.My input data is essentially of an infinite length. I tell
MediaPlayer
that its data source should basically be something like"http://localhost/myfile.mp3"
. I've a simple server set up that waits forMediaPlayer
to make this request. However,MediaPlayer
isn't very cooperative. At first, it makes anHTTP GET
and tries to grab the whole file. It times out if we try and simply dump data into thesocket
so we tried using theHTTP
Range header to write data in chunks.MediaPlayer
doesn't like this and doesn't keep requesting the subsequent chunks.Has anyone had any success streaming data directly into
MediaPlayer
? Do I need to implement anRTSP
orShoutcast
server instead? Am I simply missing a criticalHTTP header
? What strategy should I use here?-
Samuel about 13 yearsi know it late. but this is for those who end up here in the future. this Link has code to start with.
-
Mathias Conradt over 12 yearsDid you also use this approach to playback video files? Did it perform the same as audio files?
-
Ashwin N Bhanushali about 11 yearsHey Rob have you got any workaround for the issue? can you share sample code ?
-
-
ChiefTwoPencils over 9 yearsAny chance the full code is hosted anywhere? I'm trying to do the same with live video coming from the MediaRecorder + Camera and am exhausted with chasing down different attempts and libraries. If not, what size bounty would it take to add more detail here?