我的任务是制作一个嵌入页面的 mp3 播放器,该播放器将播放存储在数据库中的一些语音消息。一些消息以 WAV 格式存储,因此必须将它们转换为 mp3。转换应该“即时”完成。由于并非所有消息都必须转换,我认为使用流过滤器是个好主意,它会在需要时使用。
class LameFilter extends php_user_filter
{
protected $process;
protected $pipes = array();
public function onCreate() {
$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
//2 => array("pipe", "w"),
);
$this->process = proc_open('lame --cbr -b 128 - -', $descriptorspec, $this->pipes);
}
public function filter($in, $out, &$consumed, $closing) {
while ($bucket = stream_bucket_make_writeable($in)) {
fwrite($this->pipes[0], $bucket->data);
$data = '';
while (true) {
$line = fread($this->pipes[1], 8192);
if (strlen($line) == 0) {
/* EOF */
break;
}
$data .= $line;
}
$bucket->data = $data;
$consumed += $bucket->datalen;
stream_bucket_append($out, $bucket);
}
return PSFS_PASS_ON;
}
public function onClose() {
//$error = stream_get_contents($this->pipes[2]);
fclose($this->pipes[0]);
fclose($this->pipes[1]);
//fclose($this->pipes[2]);
proc_close($this->process);
}
}
/* Register our filter with PHP */
stream_filter_register("lame", "LameFilter")
or die("Failed to register filter");
$mp3 = fopen("result.mp3", "wb");
/* Attach the registered filter to the stream just opened */
stream_filter_append($mp3, "lame");
$wav = fopen('ir_end.wav', 'rb');
while (!feof($wav)) {
fwrite($mp3, fread($wav, 8192));
}
fclose($wav);
fclose($mp3);
在示例中,我使用了从一个文件读取并写入另一个文件的方法。但实际上数据是从 OCI-lob 读取的,必须写入 STDOUT。
问题是行“$line = fread($this->pipes[1], 8192);”实际上独立于预期的数据长度来阻止脚本。
是否有任何正确的方法来读取未关闭其 STDIN 的进程?
最佳答案
作为此解决方案的替代方案,您是否考虑过将 BLOB 保存到临时文件并使用 lame 转换临时文件,以便您可以只使用 popen() 将结果流式传输回?
关于PHP Lame 流过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3531733/