且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

流式传输到 Android MediaPlayer

更新时间:2022-11-07 13:21:30

HTTP 服务器确实托管在手机本身上.这是非常简单:只是一个 thread 监听 HTTP GET 的套接字要求.当它收到 HTTP 请求时,它会创建一个 new socket,写回一些 HTTP 标头并开始转储 MP3 音频数据回到 socket.这个 HTTP 服务器没有做任何其他事情.

The HTTP Server was indeed hosted on the phone itself. It was very simple: just a thread listening on a socket for an HTTP GET request. When it got the HTTP request, it would one a new socket, write back some HTTP headers and start dumping the MP3 audio data back to the socket. This HTTP server didn't do anything else.

Android 媒体播放器 正在播放音乐,因为我正在播放它.Media Player 如果它的播放 buffer 表现很差在播放音频时被清空.这对我来说非常重要确保我的 HTTP 服务器不断将数据写入该 socket.一世将字节以小块 (10 kB) 的形式移动到套接字中.我的标题HTTP 响应最终看起来像这样:

The Android Media Player was playing the music as I was streaming to it. The Media Player behaved very poorly if its playback buffer was emptied while it was playing audio. It was very important for me to make sure my HTTP server kept writing data into that socket. I moved bytes into the socket in small chunks (10 kB). The headers on my HTTP response ended up looking like this:

// Build response headers
StringBuilder sb = new StringBuilder();
sb.append( "HTTP/1.1 200 OK
");
sb.append( "Content-Type: audio/mpeg
");
sb.append( "Connection: close
" );
sb.append( "Accept-Ranges: bytes
" );
sb.append( "Content-Length: " + totalFileSize + "
" );
sb.append( "Content-Disposition: inline; filename=xxxxx.mp3

");

只要我一直在点燃管道,Android Media Player 就会一直保持毫无怨言地消费它.播放音频只需要一个请求和响应.结果效果很好.

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.