Ideally, I want to convert from MP3 to FLAC and back. I also need to be able to script this.
The fundamental tool for sound format conversions and simple transformations is SoX, the Swiss Army knife of sound-processing programs.
sox foo.mp3 foo.flac
If you're running Debian, support for writing MP3 in sox
is broken in lenny and squeeze (and as far as I know the same problem affects Ubuntu 10.04 and 10.10). This bug was fixed in early March 2011, so grabbing the latest source (or grabbing a binary for sox
14.3.1-1build1 or newer) and recompiling it should work.
An alternative for encoding to .mp3
is lame
. It doesn't read .flac
, but you can use sox
or flac
to convert from .flac
to .wav
and then lame
from .wav
to .mp3
.
flac -d foo.flac -c | lame - foo.mp3
sox version 13 and up supports FLAC, along with many other formats. sox can do many things to an audio file, not just convert from one format to another. It is to audio what ImageMagick is to graphics.
It's called flac
, oddly enough. It's somewhat painful to use, or was back when I scripted a transcoding job with it.
You can of course use SoX, as other people already mentioned, but I suggest using lame
and flac
:
Your first question is going from .mp3
to .flac
(see below why this is usually a bad idea):
lame --decode <file>.mp3 - | flac -o <file>.flac -
This will use WAV headers, which has limitations when it comes to very long files (four hours or more long sound files, etc.)
Your second question is how to go from .flac
to .mp3
:
flac -d -c <file>.flac | lame - <file>.mp3
These settings assume default quality levels, etc. Read the man page of lame
and/or flac
to get a better idea how to tweak them.
Now, it might just be, that you have very long recordings, which you then want to re-encode into a lossy format. This was one of my use cases, and I came up with this:
Going from .flac
to .mp3
using default quality settings:
flac -d --force-raw-format --endian=little --sign=signed <file>.flac -c | lame -r -s 48 - <file>.mp3
This assumes the raw format is a PCM data. Sample rate 48kHz, two channels. Each sample is 16bit, little endian, signed integer.
Encoding process of lame
is using default quality settings here, which might be not sophisticated enough for you, mind you.
It should be noted, that it makes no sense making a FLAC file out of an MP3 file, because the MP3 is already lossy encoded.
Going from MP3 -> FLAC and then FLAC -> MP3 makes no sense, as the quality will be impaired from the first, original MP3 encoding step.
However I assume you have a reasonable use-case for this...