Skip to content

Instantly share code, notes, and snippets.

@taicki
Created December 11, 2011 07:52
Show Gist options
  • Save taicki/1459199 to your computer and use it in GitHub Desktop.
Save taicki/1459199 to your computer and use it in GitHub Desktop.
a simple script to fix mp3 tags which have euc-kr encoding issues
#!/usr/bin/env ruby
require 'optparse'
require 'mp3info'
require 'taglib'
ID3_TAGS = [:title, :artist, :album]
options = {}
OptionParser.new do |opts|
opts.banner = 'Usage: fixtag.rb [options] [FILE|DIR]'
options[:dry_run] = false
opts.on('-d', '--dry-run', 'do not save files') do |d|
options[:dry_run] = true
end
end.parse!
def euckr_to_utf8(str)
begin
str.force_encoding('euc-kr').encode('utf-8')
rescue
nil
end
end
def update_file(fn, dry_run)
tags = {}
Mp3Info.open(fn) do |f|
ID3_TAGS.each do |tn|
converted = euckr_to_utf8(f.tag.send(tn))
tags[tn] = converted if converted
end
end
puts tags
if dry_run
return
end
frame_factory = TagLib::ID3v2::FrameFactory.instance
frame_factory.default_text_encoding = TagLib::String::UTF8
f = TagLib::MPEG::File.new(fn)
tag = f.id3v2_tag
tags.each do |tn, v|
tag.send("#{tn}=", v)
end
f.save
end
def main(args, dry_run)
args.each do |arg|
if File.file? arg
update_file(arg, dry_run)
elsif File.directory? arg
Dir.foreach(arg) do |fn|
update_file(File.join(arg, fn), dry_run) unless fn.start_with? '.'
end
end
end
end
begin
main(ARGV, options[:dry_run])
end
source "http://rubygems.org"
gem "ruby-mp3info"
gem "taglib-ruby"
GEM
remote: http://rubygems.org/
specs:
ruby-mp3info (0.6.16)
taglib-ruby (0.2.1)
PLATFORMS
ruby
DEPENDENCIES
ruby-mp3info
taglib-ruby
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment