PHP返回mp3文件

时间:2014-08-18 13:45:21

标签: php error-handling mp3

大家好!

我有一个小小的音乐应用,其中的文件是从“http://www.mymusicapp.com/get_song.php?name=SOME_MUSIC”这样的网址加载的。本地应用程序工作正常!但是,当我把它放在服务器上时,我的应用程序会在浏览器控制台中生成错误。

浏览器错误 Uncaught InvalidStateError:尝试使用不可用或不再可用的对象

我的PHP代码是......

 $song_name = $_GET['name'];
 $song_file = "{$_SERVER['DOCUMENT_ROOT']}/assets/musics/{$song_name}.mp3";

 if( file_exists( $song_file ) )
 {
      header("Content-Type: audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3");
      header('Content-Length: ' . filesize($song_file));
      header('Content-Disposition: attachment; filename="'.$song_name.'.mp3"');
      header("Content-Transfer-Encoding: binary");      
      header('X-Pad: avoid browser bug');        
      readfile( $song_file );    

  }     

1 个答案:

答案 0 :(得分:0)

也许可行:

$filename = $_GET['name'];
$real_path = "{$_SERVER['DOCUMENT_ROOT']}/assets/musics/{$filename}.mp3";
$mime_type = "audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3";
if(file_exists($real_path)) {
    header('Content-type: {$mime_type}');
    header('Content-length: ' . filesize($real_path));
    header('Content-Disposition: filename="' . $filename . '.mp3"');
    header('X-Pad: avoid browser bug');
    header('Cache-Control: no-cache');
    readfile($real_path);
} else {
    header("HTTP/1.0 404 Not Found");
}