Using php to opening live audio stream on android

爱⌒轻易说出口 提交于 2019-11-29 05:12:41

Problem

Traditionally, you would serve a playlist file which would be saved by your browser, and then opened in whatever player software was configured to open such playlists. The player would then read the URL of the stream, connect to it, and begin streaming.

On Android, they (for some crazy reason) chose not to support playlist files as supported media. Because of this, there is no direct way to launch the player using the traditional method.

Solution

On Android it seems that if you link directly to an MP3 file/stream, instead of downloading the file the default action is to open up a media player and try to stream it. This means that you can easily link directly to the URL of your stream (bypassing the playlist step entirely).

There is a catch... streams served with SHOUTcast aren't exactly HTTP compliant. They are close, but not perfect. The real hangup here seems to be one of content length. Typically, HTTP servers send a Content-Length response header. With streaming media, the length is unknown. There are two ways around the problem:

  1. Use chunked transfer encoding. You can do this by setting the following headers:
    Transfer-Encoding: chunked
    Then, use chunked encoding for the stream, and you're good to go.
  2. Use no transfer encoding, and specify that the connection will be closed when the resource is finished transferring, with these headers:
    Transfer-Encoding: none
    Connection: close

Your example link uses method one. I'm using method two successfully as well.

Once your server is talking valid HTTP, playback on Android seems to be a breeze.

Implementation

There are a handful of ways to go about implementing this fix. You have mentioned a PHP solution. If cURL won't work, you can always fsockopen() or stream_socket_client() to make a direct TCP connection, and handle the incoming stream data yourself. From there, you simply need to send the correct response headers and relay the data as it comes in. Keep in mind that a PHP instance will be running for each connected client, and each instance will make a connection to your server as well. This isn't ideal, but depending on what you have available, might be the only method for you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!