1

我想使用 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那么它就可以正常播放... ??

4

2 回答 2

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);
于 2013-10-30T00:12:24.103 回答
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);
于 2013-10-30T00:40:13.227 回答