Search

July 29, 2012

Accessing MP3 Tags in Ruby

I wanted to explore Ruby a little more so I needed to give myself a project. I figured I would try to create a script to copy a playlist to my MP3 player, since both Rhythmbox and Banshee had issues with this.

The first thing is that I would need to get the ID3 tag information from the mp3 files so I could copy them to the right filename on the mp3 player. (Both Rhythmbox and Banshee use Artist - Album - Track - Title.mp3 so I could that to check for duplicates.) So I needed to be able to read mp3 tags.

I started at the ID3 format web site, http://www.id3.org/. They had a helpful section on implementations (http://www.id3.org/Implementations) so I started there.

The first suggestion, id3lib-ruby was no longer under development. The site did suggest taglib-ruby but I decided to move to the next one.

The next one was ruby-mp3info. I rejected that one on the basis that the installation used Ruby’s gem utility. (That later turned out to be a mistake.)

The final one was id3.rb and I did download the gem. But the documentation was a little thin and it felt too much like a side project for a university student.

I decided to fire up synaptic and see if there was a package. Lo and behold, there was one for ruby-taglib. I installed it and tried the following simple script:

require 'taglib'

ARGV.each do |f|
  TagLib::FileRef.open(f) do |fileref|
    tag = fileref.tag
    puts "#{f}: #{tag.title} by #{tag.artist}; track #{tag.track} on #{tag.album}"
  end
end

Unfortunately the result was: NameError: uninitialized constant TagLib::FileRef. I puzzled over this for a while and examined the documentation and probed the Ruby object to no avail. Eventually I decided to try installing via the gem method. No luck that way, same result.

Finally it occurred to me that the two installations might be conflicting. I uninstalled both and re-installed via gem install taglib-ruby. Now my script worked.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.