Convert WAV to MP3 using LAME from PHP

I have WAV data that I would like to convert to MP3 on the fly using a PHP script. A WAV file starts with a script, so it does not run as a file.

I can run something like this:

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

But for this you will need to first write in.wav to disk, read .mp3 from disk, and then clear it when I finish. I would rather not do this. Instead, I have a wav file stored in $ wav, and I would like to run it through LAME so that the resulting data is then saved in $ mp3.

I saw links to the FFMPEG PHP library, but I would prefer not to install any additional libraries for this task, if possible.

+4
source share
1 answer

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

Where:

  • $ wav is the source WAV data to convert.
  • $ mp3 contains 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 output is identical if I /usr/bin/lame --cbr -b 32k in.wav out.mp3 .

+7
source

Source: https://habr.com/ru/post/1493886/


All Articles