holamendi
1/26/2013 - 10:58 PM

Ruby script I use to convert FLAC files to MP3, and then copy the metadata across.

Ruby script I use to convert FLAC files to MP3, and then copy the metadata across.

#!/usr/bin/env ruby
# encoding: UTF-8

# Convert FLAC files to mp3 files, keeping metadata from the FLAC files.
#
# Requires that FLAC (including metaflac) and LAME tools be installed
# and on the path.
#
# Takes any number of .flac files on the command line.

require 'tempfile'

def flactags(filename)
  tmpfile = Tempfile.new('flacdata')
  system(
    'metaflac',
    "--export-tags-to=#{tmpfile.path}",
    '--no-utf8-convert',
    filename
  )
  data = tmpfile.open
  info = { 'title' => '', 'artist' => '', 
  'album' => '', 'date' => '', 
  'tracknumber' => '0' }
  while line = data.gets
    m = line.match(/^(\w+)=(.*)$/)
    if m && m[2]
      puts line
      info[m[1].downcase] = m[2]
    end
  end
  return info
end

def encode(filename)
  basename = filename.sub(/\.flac$/, '')
  wavname = "#{basename}.wav"
  mp3name = "#{basename}.mp3"
  info = flactags(filename)
  track = info['tracknumber'].gsub(/\D/,'')
  system(
    'flac',
    '-d',
    '-o',
    wavname,
    filename
  )
  system(
    'lame',
    '--replaygain-accurate',
    '--preset', 'cbr', '320',
    '-q', '0',
    '--add-id3v2',
    '--tt', info['title'],
    '--ta', info['artist'],
    '--tl', info['album'],
    '--ty', info['date'],
    '--tn', track,
    '--tg', info['genre'] || 'Rock',
    wavname,
    mp3name
  )
  FileUtils.rm(wavname)
end

if ARGV.length == 0
  puts "#{File.basename($0)} file1.flac file2.flac ..."
else
  for file in ARGV
    encode file
  end
end