Quantcast
Channel: Mark P. Lindhout’s Flamepit » News
Viewing all articles
Browse latest Browse all 10

Converting FLAC files to MP3 with FFmpeg and Bash

$
0
0

Yes, yes, I know, the title of this post is 100% geek-approved. All those acronyms mean little to most people, but I will explain.

Recently, a friend of mine started converting his music into FLAC, the Free Lossless Audio Codec. The name says it, it’s lossless. That is a plus, but since I don’t have a gazillion terabytes on my mobile phone, and would still like to check out some music he sends me now and then, I need my music to be old-school MP3.

Knowing the power of FFmpeg, I was thinking there must be a cool one-liner out there somewhere. However, most of the code I found was either too old, or not exactly tailored to what I was looking for. Therefor I’m publishing my snippet here, as much for myself (I am prone to forgetting this kind of stuff) as well as for the benefit of others.

Convert all FLAC files in a directory into MP3 files with FFmpeg.

$ (for FILE in *.flac ; do ffmpeg -i "$FILE" -f mp3 -ab 192000 "`basename "$FILE" .flac`.mp3" || break; done)

A little explanation; The brackets around the command allow for a nice interrupt when the user presses CTRL+C. This is practical especially when you’re processing many files. Seeing as we’re processing an album here, 15 files is no exception, and who wants to be pressing CTRL+C 15 times, right?

The for loop should be self-explanatory, but it has a little addition to a normal loop. The || (double pipe) makes sure all processing is done before the loop breaks. So, when an instance of ffmpeg exits with something else than status code 0, it will break the loop. Basically, it says: encode the file OR stop. This is handy for possible errors in the middle of a file set. You would like to see where it all failed, not end up with some corrupted files somewhere halfway and not know what’s going on.

The basename part makes sure the extension is changed from .flac to .mp3. If you would just drop the $FILE variable in there, you’d end up with files named cool-songtitle.flac.mp3.

Setting the bit rate in FFmpeg is easy. You can use the -ab option to set the bit rate in bits. (This is straight from the FFmpeg documentation, by the way) I used 192 kilobits, but you can use anything, really. Remember: the higher the bit rate, the larger the file.

Selecting input files is done by adapting the *.flac and `basename "$FILE" .flac` parts to your needs. You can input basically anything that FFMpeg can understand, which includes WAV, OGG, ACC, AVI, MPEG, MP3, FLAC and many, many more. For a complete list check out the list of FFmpeg supported formats.

The same goes for selecting the output format, in this case you adjust all occurrences of mp3 to your needs.

So, after this elaborate explanation of a small but useful snippet, what do you think?


Viewing all articles
Browse latest Browse all 10

Trending Articles