问题
I'm trying to send my mp3 files through a PHP script in order to hide the path to the file in the HTML. Everything works perfectly fine except half way into the mp3 chrome gives me a GET [URL] error. And the rest of the mp3 is just blank. The audio tag thinks it's still reading the file, but there is no sound.
This is how I'm sending the mp3 file from php:
if (file_exists($filename)) {
header("Content-Transfer-Encoding: binary");
header("Content-Type: audio/mpeg");
header('Content-length: ' . filesize($filename));
header('Content-Disposition: inline; filename="' . $filename . '"');
header('X-Pad: avoid browser bug');
header('Cache-Control: no-cache');
readfile($filename);
exit;
}
else {
header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found', true, 404);
echo "no file";
}
Edit: I added the Etag header. It seems to make things better. The problem still occurs but not as often. :-/
Edit2: I have noticed that the request headers sent to my PHP file is different from the headers sent directly to the mp3 file. Actually there's a HTTP_RANGE request sent to the mp3 file, but this range request is missing when I try to fetch things from PHP. (This is in Chrome). Any idea why this might be ?
回答1:
I know this is an old post but I was able to get this working with two files and index.php and example.php.
this is example.php that's checking a databse for a hash and a used field to know if the file has been used before
<?php
if(isset($_GET['hash'])){
$mysqli = new mysqli('host_here','user_here','password_here','database_here');
$result = $mysqli->query("select * from hashes where hash = '{$_GET['hash']}' limit 1");
$row = $result->fetch_array();
}
if(isset($row['used']) && $row['used'] == 0){
$mysqli->query("update hashes set used=1 where hash = '{$_GET['hash']}'");
$filename = "example.mp3";
header("Content-Transfer-Encoding: binary");
header("Content-Type: audio/mpeg");
header('Content-length: ' . filesize($filename));
//If this is a secret filename then don't include it.
header('Content-Disposition: inline');
//Otherwise you can add it like so, in order to give the download a filename
//header('Content-Disposition: inline;filename='.$filename);
header('Cache-Control: no-cache');
readfile($filename);
exit;
}
elseif(isset($row['used']) && $row['used'] == 1){
die("you can't just download this dude");
}
and here is index.php with the audio tag that will allow playing but not downloading of the mp3.
<html>
<body>
<?php
$mysqli = new mysqli('localhost','root','','test_mp3');
$rand = mt_rand();
$hash = md5($rand);
$result = $mysqli->query("insert into hashes (hash,used) values('$hash',0)");
?>
<audio controls>
<source src="example.php?hash=<?=$hash?>" type="audio/mpeg">
</audio>
</body>
</html>
there is a database table with just a hash and a used field for this example to work
来源:https://stackoverflow.com/questions/9627678/sending-mp3-file-through-php-to-be-used-with-the-audio-tag-of-html5-fails-in-the