Pregunta

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.

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top