Skip to content

Instantly share code, notes, and snippets.

@almokhtarbr
Forked from lpar/flac2mp3.rb
Created March 8, 2022 21:12
Show Gist options
  • Save almokhtarbr/147e02736abb5ceb78740fcaf278e37f to your computer and use it in GitHub Desktop.
Save almokhtarbr/147e02736abb5ceb78740fcaf278e37f to your computer and use it in GitHub Desktop.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment