我想用PHP从文件中读取并流式传输出去。
我的代码看起来像这样:
测试流.php
$bufsize=4096; // amount of buffer to read at a time.
$h = fopen("test.wav", "rb");
$stdout = fopen("php://stdout", "wb");
while ( !feof($h) ) {
$buf = fread($h, $bufsize);
fwrite($stdout, $buf);
}
pclose( $h );
然后我希望能够将其放入媒体播放器(例如VLC)中,例如:
http://www.test.com/teststream.php
这种方法不起作用,我也不确定为什么。
----更新的代码现在如下所示:
<?php
$bufsize=4096; // amount of buffer to read at a time.
$h = fopen(dirname(__FILE__)."/test.wav", "rb");
header("Content-Type: audio/x-wav", true);
$stdout = fopen("php://stdout", "wb");
$total=0;
while ( !feof($h) ) {
$buf = fread($h, $bufsize);
$total=$total+strlen($buf);
error_log("buf read: ".strlen($buf).", total: ".$total);
fwrite($stdout, $buf);
}
fclose( $h );
Apache error_log看起来像这样:
[Wed Oct 30 00:29:12 2013] [error] [client 50.201.227.222] buf read: 4096, total: 4096
[Wed Oct 30 00:29:12 2013] [error] [client 50.201.227.222] buf read: 4096, total: 8192
[Wed Oct 30 00:29:12 2013] [error] [client 50.201.227.222] buf read: 4096, total: 12288
...
...
所以它看起来像是在发送数据,但它从不在VLC端播放音频。 如果我将VLC指向 http://www.test.com/test.wav 那么它播放得很好... ??
我在我的一个项目中做了这个,它就像一个魅力:
//send file contents
$fp=fopen(dirname(__FILE__) . "/test.wav", "rb");
header("Content-type: application/octet-stream");
header('Content-disposition: attachment; filename="test.wav"');
header("Content-transfer-encoding: binary");
header("Content-length: ".filesize(dirname(__FILE__) . "/test.wav")." ");
fpassthru($fp);
fclose($fp);
PHP 是否报告任何错误?也许它找不到测试,.wav。如果此文件与 PHP 脚本位于同一文件夹中,只需将代码更改为以下内容:
$bufsize=4096; // amount of buffer to read at a time.
$h = fopen(dirname(__FILE__) . "/test.wav", "rb");
$stdout = fopen("php://stdout", "wb");
while ( !feof($h) ) {
$buf = fread($h, $bufsize);
fwrite($stdout, $buf);
}
pclose( $h );
哦..是的,在输出中添加一个标题,如下所示:
header("Content-Type: audio/x-wav", true);