我想使用PHP从文件中读取并将其流出。
我的代码看起来像这样:
teststream.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,那么它可以正常播放...... ??
答案 0 :(得分:0)
PHP是否报告任何错误?也许它找不到test.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);
答案 1 :(得分:0)
我在我的一个项目中做到了这一点,它就像一个魅力:
//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);