Thursday, November 29, 2012

Transcode files of different formats

Some times FLAC is nice, sometimes MP4 videos are neat.
Sometimes though, you have an SD card that's too small, or a device with limited output quality, or decoding resources, and what you want is Mp3 in a space-saving, but still nice-enough sounding Variable Bit Rate (VBR).

Maybe it's a playlist for a mobile device? Who knows..
But when things like that happen, and you have a directory full of files, here's what you do:

mkdir out
ls | while read L
do
  IN="$L"
  OUT=`echo "$IN" | sed 's/\(.*\)\..*/\1/'`
  ffmpeg -i "$IN" -aq 1 -vn -map_metadata 0 "out/$OUT.mp3"
done


This loops through all files, cuts off their extention, and trancodes them to variable bitrate between 190-250 Kbit/s ( http://ffmpeg.org/trac/ffmpeg/wiki/Encoding%20VBR%20%28Variable%20Bit%20Rate%29%20mp3%20audio )
Notice the -vn option, which, in case it's video, greatly speeds up encoding by ignoring the video part of the input file.
The -map_metadata 0 attempts to take the first chunk of metadata from the original file, and save its fields in the newly encoded mp3 file, milage may vary, it worked in most of my files.

Your files end up in the "out" directory.

I came up with this when assembling a playlist for my phone, not needing (or wanting to waste space on) super high quality, or music videoes.. Amongst input files were FLAC, Mp3, Ogg and video-files in avi and mp4 containers.