与DB通信后,使用PHP输出MP3文件


Output MP3 file with PHP after communication with DB

我有一个允许用户播放MP3的网站,但我想知道每个文件播放了多少次。我尝试搜索以查看如何使用PHP输出MP3,我认为您可以通过调用header('Content-Type')来完成,但我找不到任何文档。

假设我有一个文件,/music/song.mp3,并且我已经完成了数据库交互代码并且没有将输出发送到浏览器,我需要传递哪些标头才能在完成数据库交互后允许 MP3 输出?

更新:这是我现在使用的,该页面下载了具有正确文件名的mp3,但它已损坏并且无法播放。知道这是为什么吗?

$track = $_GET['t'];
header('Content-type: audio/mpeg');
header('Content-length: ' . filesize($_SERVER['DOCUMENT_ROOT'].'music/'.$track.'.mp3'));
header('Content-Disposition: attachment; filename="'.$track.'.mp3"');
header("Content-Transfer-Encoding: binary");
header("Content-Type: audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3");

这是一个链接,您可以在其中测试 mp3:http://shacktown.com/engine/api/mp3/?t=giftofmelody

您的header应如下所示:

$file = "/some/folder/your.mp3";
header('Content-type: audio/mpeg');
header('Content-length: ' . filesize($file));
header('Content-Disposition: attachment; filename="your.mp3"');
header("Content-Transfer-Encoding: binary"); 
header("Content-Type: audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3");
readfile($file);

我最终只是将信息记录到数据库,然后转发到源文件。我尝试了您更新的示例,但无法正确读取文件。如果有人想知道,这就是我现在使用的代码,并且在功能上它可以根据需要工作。

$trackPath = $_SERVER['DOCUMENT_ROOT'].'music/'.$track.'.mp3';
if ( !file_exists($trackPath) )
    die('no!');
$trackInfo = $db->Fetch('tracks', 'plays', 'src="'.$track.'"');
$update = $db->Update('tracks', array('plays'=>$trackInfo['plays']+1), 'src="'.$track.'"');
header('Location: http://shacktown.com/music/'.$track.'.mp3');

$db 是我为便于查询而制作的数据库对象的简写,但我认为这是不言自明的。