【问题标题】:Using PHP to create a stream -使用 PHP 创建流 -
【发布时间】:2013-10-30 00:05:03
【问题描述】:

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

【问题讨论】:

  • 您可能需要发送一个header,内容类型我假设是视频类型。此外,pclose 用于 popen。你可能想要fclose
  • 我确实添加了 -- header("Content-type: audio/wav");但这似乎没有什么不同。另外 - 是的,我实际上正在尝试做一些不同的事情,但是,是的,你对 pclose 的看法是正确的。
  • 正如 Steyx 所说,有什么错误吗?如果您删除标题,您是否看到任何输出?如果没有标题,您应该会看到原始文件,就像您在文本编辑器中打开它一样。如果您没有看到任何内容,请检查您的错误日志中是否存在致命错误。
  • VLC 只是跳过它到下一个文件。我尝试了下面的答案建议的更改,然后它就挂了 - 但至少它停留在那个流上......

标签: php stream media


【解决方案1】:

我在我的一个项目中做到了这一点,它就像一个魅力:

//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);

【讨论】:

  • 那么 fpassthru 和 fwrite 有什么区别?
  • 有时 php://stdout 不能正常工作。另一件事是您发送的标题。您可以尝试使用混合方法并查看结果。
  • 我可以使用这个php流脚本同时为多个用户使用它吗? @bksi
【解决方案2】:

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-22
    • 2011-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多