I'm trying to provide a audio file through a browser using HTML5 audio tag:
<audio preload="auto">
<source src="<?php echo $song->getUrl('mp3'); ?>" type="audio/mpeg">
<source src="<?php echo $song->getUrl('ogg'); ?>" type="audio/ogg">
Please update your browser.
</audio>
I need to save traffic, so I thought about sending partial content this way:
$contentType = ($format == 'mp3') ? 'audio/mpeg' : 'audio/ogg';
$filePath = $song->getPath($format);
$fileLength = filesize($filePath);
$start = 0;
if(isset($_SERVER['HTTP_RANGE']) && !empty($_SERVER['HTTP_RANGE'])) {
$http_range = explode('-', substr($_SERVER['HTTP_RANGE'], strlen('bytes=')));
$start = $http_range[0];
}
$remainingBytes = $fileLength - $start;
$length = min((512*1024), $remainingBytes);
$final = $start + $length;
header('HTTP/1.1 206 Partial Content');
header('Status: 206 Partial Content');
header('Content-Type: ' . $contentType);
header('Content-Disposition: inline;filename="listen.' . $format . '"');
header('Content-length: ' . $length);
header('Content-Transfer-Encoding: bytes');
header('Accept-Ranges: bytes');
header('Cache-Control: no-cache');
header('Content-Range: bytes ' . $start . '-' . $final . '/' . $fileLength);
echo file_get_contents($filePath, false, null, $start, $length);
The result of this is, in Chrome, the song being almost completely played (3.41 out of 3.47 seconds of a 9.1MB file). In firefox, the first 39 seconds played (I guess 512KB). In opera, a never-ending "loading" status.