Skip to main content

Stream Audio to an HTML5 Audio Element

· One min read
Apache Wangye
Software developer and technical writer

An <audio> element can play a normal HTTP resource, but seeking and reliable playback depend on correct response headers and byte-range support.

<audio controls preload="metadata" src="/media/song.mp3"></audio>

The server should send the real media type, such as audio/mpeg, and a correct Content-Length. When the request contains Range: bytes=start-end, validate the range and return:

HTTP/1.1 206 Partial Content
Accept-Ranges: bytes
Content-Range: bytes start-end/total
Content-Length: selected-length
Content-Type: audio/mpeg

Stream only the requested bytes instead of loading the complete file into memory. Reject invalid or unsatisfiable ranges with 416 Range Not Satisfiable.

Support HEAD, conditional requests, and appropriate cache headers when needed. Keep path resolution inside an authorized media directory and enforce access control before opening a file. Browser codec support varies, so provide formats supported by the target platforms or use a transcoding pipeline.

Page views: --

Total views -- · Visitors --