[英]Pushing file to web-browser while being written
我有一個后台ffmpeg進程正在輸出音頻文件,我想將此文件推送到用戶Web瀏覽器,而ffmpeg繼續在該文件上寫入。 我嘗試了以下操作,但這發送了0個字節的文件。
// open the file in a binary mode
$fp = fopen($fname, 'rb');
// send the right headers
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($fname));
ob_end_clean();
fpassthru($fp);
exit;
ffmpeg無法從PHP / Python啟動並在此處捕獲輸出。
fpassthru
函數不會在這里完成工作。 另外,知道文件何時完成將存在一個問題。
到達文件末尾時,文件讀取功能停止。 如果有一個並發的寫程序增加了文件的長度,則它不確定在看到EOF之前閱讀器將走多遠。 另外,沒有明確的方法-通過文件操作-知道文件編寫器是否完成。
嘗試使用這樣的循環(偽代碼)嘗試超時讀取是可行的:
LOOP
READ bytes
IF count read == 0
THEN
SLEEP briefly
INCREMENT idle_count
ELSE
SET idle_count = 0
WRITE
END IF
UNTIL ( idle_count == 10 )
如果有幫助,我可以將其放入PHP代碼中。
這是使用兩個文件in.dat
和out.dat
此操作的PHP代碼:
<?php
$in_fp = fopen("./in.dat", "r");
$out_fp = fopen("./out.dat", "w");
$idle_count = 0;
while ( $idle_count < 10 )
{
if ( $idle_count > 0 )
sleep(1);
$val = fread($in_fp, 4192);
if ( ! $val )
{
$idle_count++;
}
else
{
$idle_count = 0;
$rc = fwrite($out_fp, $val);
if ( $rc != strlen($val) )
die("error on writing of the output file\n");
}
}
請注意,睡眠的奇數位置是為了防止在最后一次嘗試讀取后一秒鍾進入睡眠狀態。
為此,我建議將空閑超時限制設置為大於10。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.