douhui3760 2011-03-11 15:50
浏览 137
已采纳

用php输出mp3

I'm working on my school project and I'm trying to output a mp3 file using PHP but apparently it just outputs some corrupt file and I have no clue why. I browsed the entire net to find a solution, but no.

<?php
$filename = 'audio/1/1.mp3';

if(file_exists($filename)) {
    header('Content-Type: audio/mpeg');
    header('Content-Disposition: filename="test.mp3"');
    header('Content-length: '.filesize($filename));
    header('Cache-Control: no-cache');
    header("Content-Transfer-Encoding: chunked"); 

    readfile($filename);
} else {
    header("HTTP/1.0 404 Not Found");
}
?>

Can anyone explain this to me? That would be totally awesome!

  • 写回答

3条回答 默认 最新

  • duanmajing9332 2011-03-15 12:32
    关注

    Well the answer was way off and it wasn't my script. Before any HTML tag I load all content, if custom headers are defined I only show the content (retrieved from templates)

    <?php
    //get stuff
    if(empty($page->customHeader)): ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title><?php print $page->title ?></title>
    </head>
    
    <body>
    <div class="container">
        <div class="header">
        </div>
    
        <div class="content">        
            <?php print $page->content ?>
        </div>
    
        <div class="footer">
        </div>
    </div>
    </body>
    </html>
    <?php else:
        print $page->content;
    endif; ?>
    

    For the templates i use ob_get_contents(), so in the actual template I echo/print data. For some reason ob_get_contents() doesn't fetch that properly so that's where it went wrong.

    Now I define my headers in an array and the path of the content in another variable and call that.

    ...
    </html>
    <?php else:
        foreach($page->customHeader as $header) {
            header($header, true);
        }
    
        readfile($page->headerContent);
    endif; ?>
    

    Long story short: ob_get_contents() doesn't get binary content.

    Thanks guys, definately going to give you thumbs up for the efford and rather useful information!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog