Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Streaming MP3

I have a very similar situation to the person who asked: Can I serve MP3 files with PHP? Basically I am trying to protect mp3 files from direct download, so users have to go through php to get authenticated first. Here's my code:

header('Content-type: audio/mpeg');
header('Content-length: ' . filesize($file));
header('X-Pad: avoid browser bug');
Header('Cache-Control: no-cache');
header("Content-Transfer-Encoding: binary"); 
header("Content-Type: audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3");
readfile($file);

Here's my problem: The file only plays a very small chunk of the beginning (via Quicktime in the browser) and then stops - Quicktime seems to think the length of the file is only as long as the chunk it managed to download. When I reload - it plays a slightly larger chunk - whatever it managed to download up to that point.

Is that a problem in the headers I am sending? How would I stream such a file? Is it a problem if an swf is reading from that file?

Thanks!


Thank you guys for all the answers. Although none of these things were exactly what solved the problem, many of them sent me in the right direction. Much appreciated. For the full solution see my answer below

like image 564
Yuval Karmi Avatar asked Mar 01 '10 18:03

Yuval Karmi


2 Answers

Here's what did the trick.

$dir = dirname($_SERVER['DOCUMENT_ROOT'])."/protected_content";
$filename = $_GET['file'];
$file = $dir."/".$filename;

$extension = "mp3";
$mime_type = "audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3";

if(file_exists($file)){
    header('Content-type: {$mime_type}');
    header('Content-length: ' . filesize($file));
    header('Content-Disposition: filename="' . $filename);
    header('X-Pad: avoid browser bug');
    header('Cache-Control: no-cache');
    readfile($file);
}else{
    header("HTTP/1.0 404 Not Found");
}
like image 80
Yuval Karmi Avatar answered Nov 04 '22 23:11

Yuval Karmi


You can try HTTP chunking. Set the "Transfer-Encoding" header to "chunked", then output the size of each chunk before sending it. End each chunk size and chunk with a CRLF.

For anything more complex, I recommend using a streaming server, such as Icecast.

like image 42
outis Avatar answered Nov 04 '22 23:11

outis