将MP3流式传输到浏览器,而不是将数据另存为文件


stream mp3 to the browser instead of saving the data as a file

我正在使用以下php类将文本转换为语音: http://www.masnun.me/2009/12/14/googles-text-to-speech-api-a-php-wrapper-class.html

它使用 Google 的 API,现在代码将文件保存在本地,但我希望它强制将文件流式传输到用户的浏览器。 这就是我想出的:

function saveToFile($filename) {
    $filename = trim($filename);
    if(!empty($filename)) {
            header("Content-type: application/octet-stream");
            header('Content-length: ' . filesize($this->mp3data));
            header('Content-Disposition: filename="' . $filename);
            header('X-Pad: avoid browser bug');
            header('Cache-Control: no-cache');
            readfile($this->mp3data);
    } else { return false; }
}

但是生成的文件是0KB空的MP3文件。 我做错了什么?

readfile()接受文件名作为参数,而不是文件的内容。尝试将读取文件行替换为以下内容:

echo $this->mp3data;

readfile实际上会回显到浏览器吗?如果它只是返回一些东西,它将无法按您的预期工作:

echo readfile($this->mp3data);

我也了解 readfile 适用于路径,如果是这种情况,请尝试:

echo $this->mp3data;