php streaming or buffering mp3 file problem
I built a mp3 playing website.
I use a flash mp3 player to play the mp3 file.It can play, but it can not load the correct time and not stream and buffer the mp3 file located on my server.
It can play the mp3 file correctly if the url is from other site, like Google music.
I think the important problem is the header output of the mp3 file.
this is the code of my php file to output the mp3 开发者_StackOverflow中文版file.
<?php
$filename='music/'.$_GET['id'].'.mp3';
$fileSize=filesize($filename);
header('Accept-Ranges: bytes');
header('Cache-Control: max-age=604800');
header('Content-Length: ' . $fileSize);
header('Content-type: audio/mpeg');
readfile($filename);
?>
can anyone tell me what`s the problem is?
PS: You can test on Chrome. Just use Chrome to open the file or page, it will display a player to play mp3 file.
I experienced this problem, too. I solved it using PHP's readfile()-function. I do not know why it worked, but it did. Besides, it shortens your code and uses less memory:
$filename = 'music/'.$_GET['id'].'.mp3';
header('Cache-Control: max-age=604800');
header('Content-type: audio/mpeg');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($filename));
readfile($filename);
OK, the problem solved. The actually problem is the Liunx system (Like CentOS and Ubuntu) do not support mp3 streaming.
To solve the problem, you have to install gnump3d to enable streaming server.
my site mu6.me can play the music like other music website now.
For one, using the 'Accept-ranges' header means your script is telling the browser it can request specific portions of the file, but you're unconditionally sending the entire thing. At least switch to using none
instead of bytes
to indicate that you're not allowing range requests, or eliminate the header entirely.
Second, doing:
print(fread($mp3, $fileSize - 10000 ));
is odd. Regardless of how big or small the mp3 actually is, you'll be sending it in at most two chunks. The first chunk will be the entire file minus the last 10,000 bytes, and the second chunk (if the file's > 10,000 bytes long) will be that final up-to-10,000 bytes. If you have a large-ish mp3, sending it this way may exceed php's memory_limit and kill the script. The mp3 player may not notice this as it'll be happily playing the portion of the tune that's already been sent. Instead of the whole fopen/while/fclose business, just use readfile()
which will properly send the file in small enough chunks so as to not exceed memory limits.
have you tried adding a file name?
header('Content-Disposition: attachment; filename="media.mp3"');
header('Pragma: no-cache');
Hope this helps
精彩评论