Tuesday, October 27, 2015

Mac OS X Automator - Convert .m4a to .mp3

I had a problem that my car stereo only plays MP3 files, but I have some music in M4A format that I wanted to listen to for a road trip.

So I wanted to convert it, and as I had a few files to do, I decided that Automator could help me out in order to repeat it.

In the end it was pretty simple.
I created a new Automator application in case I wanted to have it as an application in the future. You could do it as a workflow as well, since if you compile it as an application the paths will be set inside it and you will have to open it in Automator again to change it.


I already had ffmpeg on my system so I tested it on the command line first.

If you don't have ffmpeg installed you can install it with Macports using the command:

sudo port install ffmpeg 

Once you have the ffmpeg installed, play around with for a bit to get it converting the audio file on the command line. Once that was working all you needed to do was have your Automator application get a finder object and run a shell script using the ffmpeg command line options with a few adjustments (such as needing the ffmpeg complete path in Automator)



Here is the code:

for f in "$@"
do
b=$(basename -s .m4a "$f")
/opt/local/bin/ffmpeg -i "$f" -codec:a libmp3lame -ab 256k /Users/username/Desktop/"$b".mp3
done

(If you copy the above code, don't forget to change the output directory to the one you want)

That basically creates a loop that goes through all of your input files. The screenshot only had one input, but you can drag multiple files into the "get specified finder items" section. Each time the loop runs the current file it is working on gets saved into variable 'f'.

b=$(basename -s .m4a "$f") -> creates a variable 'b' and saves into it, the filename of the current file we are working on (that is "$f" dont forget) without the .m4a extension. So if you pass it '/path/to/file/music.m4a' variable 'b' will contain 'music'

Then run the ffmpeg command line. In my case I knew the input bitrate was 256kbps, so I forced ffmpeg to save in that bitrate too. Check the ffmpeg documentation for what you can do with it.