Skip to content

Instantly share code, notes, and snippets.

@shenie
Created October 5, 2011 03:18
Show Gist options
  • Save shenie/1263537 to your computer and use it in GitHub Desktop.
Save shenie/1263537 to your computer and use it in GitHub Desktop.
Fix mp3 meta tags based on filename & path
# A sample Gemfile
source "http://rubygems.org"
# gem "rails"
gem 'ruby-mp3info'
GEM
remote: http://rubygems.org/
specs:
ruby-mp3info (0.6.16)
PLATFORMS
ruby
DEPENDENCIES
ruby-mp3info
#!/usr/bin/env ruby
require 'rubygems'
require 'mp3info'
require 'fileutils'
def parse_dirname(str)
album = File.basename str
artist = File.dirname str
if artist == '.'
artist = album
album = nil
end
[artist, album]
end
def parse_filename(str)
str = str[0..-5]
parts = str.split('-')
raise str if parts.size > 3
artist = nil
album = nil
title = nil
if parts.size == 1
title = parts.first
elsif parts.size == 2
artist = parts.first
title = parts.last
elsif parts.size == 3
(artist, album, title) = parts
end
title = filter_title(title)
[artist, album, title]
end
def filter_title(s)
s = s.gsub(/^[0-9]+[ \.]*/, '')
end
Dir["**/*.[mM][pP]3"].each do |f|
filename = File.basename f
dirname = File.dirname f
has_dir = dirname != '.'
puts "=" * 20
puts " file: #{f}"
artist = ''
album = ''
title = ''
if has_dir
(artist, album) = parse_dirname(dirname)
title = filename[0..-5]
title = filter_title(title)
if title =~ /-/ && !album
parts = title.split('-')
album = parts.first
title = parts[1..-1].join('-')
end
else
(artist, album, title) = parse_filename(filename)
end
artist.strip! if artist
album.strip! if album
title.strip! if title
puts "artist: '#{artist}'" if artist
puts "album : '#{album}'" if album
puts "title : '#{title}'"
puts ""
Mp3Info.open(f, :encoding => 'utf-8') do |mp3|
mp3.tag.artist = artist
mp3.tag.album = album
mp3.tag.title = title
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment