Saturday, November 06, 2010

FLAC encoding to MP3 and Ogg

Okay, so you have a collection of amazing music in FLAC. But your portable media player only supports MP3. That means you have to convert the files before you can put them on your player. And it would be nice to convert whole albums.

If your player supports Ogg, you can simply execute this. It converts each of the .flac files in the current directory to Ogg.

oggenc -q7 *.flac

But how about MP3? LAME is a terrific MP3 encoder, but it doesn’t have an option to convert FLAC files.

Well, fortunately, Linux provides all the needed tools to get the needed combination of programs working together to do something.

for i in *.flac ; do flac -dc "${i}" | lame -b 320 --alt-preset insane - "/home/ml/mp3/${i%.flac}.mp3" ; done

Here we use the “for” cycle of bash to run the “flac” command for each of the .flac files in the current directory. Option -d tells flac to decode the given file and -c tells to write output to the standard output (stdout). LAME has two required arguments: input file and output file. But we can use a hyphen (“-”) for input file to use stdin and for output file to use stdout. In this case LAME has stdin received from flac. To transmit flac’s output to lame’s input we used pipes. Finally, ${i%.flac}.mp3 is a simple bash parameter substitution example. It takes the contents of the i variable, but without the ending “.flac”. Then you can just put .mp3 to the end of the string to make a new file extension.

No comments: