Convert WAV to MP3 using LAME from PHP

做~自己de王妃 提交于 2019-12-06 03:29:12

问题


I have WAV data that I'd like to convert to MP3 on the fly with a PHP script. The WAV file originates with the script, so it does not start out as a file.

I can run something like this:

exec( "lame --cbr -b 32k in.wav out.mp3" );

But this will require that I first write in.wav to disk, read out.mp3 from disk, and then clean up when I'm finished. I'd prefer not to do that. Instead, I have the wav file stored in $wav, and I'd like to run this through LAME such that the outputted data is then stored in $mp3.

I've seen references to an FFMPEG PHP library, but I'd prefer to avoid having to install any additional libraries for this task if possible.


回答1:


It appears that proc_open() is what I was looking for. Here's the snippet of code I wrote and tested that does exactly what I was looking for:

Where:

  • $wav is the original WAV data to be converted.
  • $mp3 holds the converted MP3 data,
$descriptorspec = array(
    0 => array( "pipe", "r" ),
    1 => array( "pipe", "w" ),
    2 => array( "file", "/dev/null", "w" )
);

$process = proc_open( "/usr/bin/lame --cbr -b 32k - -", $descriptorspec, $pipes );

fwrite( $pipes[0], $wav );
fclose( $pipes[0] );

$mp3 = stream_get_contents( $pipes[1] );
fclose( $pipes[1] );

proc_close( $process );

The final outputted data is identical to if I had run /usr/bin/lame --cbr -b 32k in.wav out.mp3.



来源:https://stackoverflow.com/questions/17905583/convert-wav-to-mp3-using-lame-from-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!