Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Ruby on Rails (http://www.go4expert.com/articles/ruby/)
-   -   Read & Update MP3 ID3 Tags in Ruby (http://www.go4expert.com/articles/read-update-mp3-id3-tags-ruby-t29652/)

pradeep 3May2013 19:35

Read & Update MP3 ID3 Tags in Ruby
 
ID3 is a format to store metadata within MP3 files which might include album info, artist info, cover images, thumbnails, and so on. These tags help software like Windows Media Player, iTunes, etc. categorize music and build a library for you to browse. Also, there exists software like Easy ID3 Tag Editor, etc. which allow you to create and edit ID3 tags' all fields.

So, what's the use? There are many, you might want to create your own web-based ID3 editor/library, or you might want to create an index of MP3 files you have and so on.

In this article we'll be looking at a Ruby module called taglib-ruby which is a Ruby interface for the C++ library called taglib. We'll use the Ruby module to read & write to MP3 files' tags. TagLib also supports many other file formats like OGG, FLAC, etc, but here we will only be looking at MP3.

Installing TagLib for Ruby



You'll need to install taglib library (http://taglib.github.io/), if your system's package manager can install it then fine, else you'll need to compile it.

After installing taglib library, issue the following command to install taglib-ruby.

Code:

$ gem install taglib-ruby


That's all, now we can start reading ID3 tags from MP3 files.

Reading Tags for MP3



Let's lay hands on some code which will read tags from an MP3 and print them out:

Code: Ruby

require 'rubygems'
require 'taglib'

TagLib::MPEG::File.open("disco_dewane.mp3") do |mp3_file|
    ## ID3 tag
    tag = mp3_file.id3v2_tag
    ## properties of the audio like bitrate, length etc.
    properties = mp3_file.audio_properties

    ## print some details
    print properties.bitrate ## bit rate in kilobits/sec
    print properties.length ## length in seconds

    print tag.title
    print tag.artist
    print tag.album
    ## and so on
end


I guess that was self explanatory enough.

Writing/Updating Tags



Writing is quite similar to ready, we can also add album art images, cover images if we want, follow the code example below:

Code: Ruby

require 'rubygems'
require 'taglib'

TagLib::MPEG::File.open("disco_dewane.mp3") do |mp3_file|
    ## ID3 tag
    tag = mp3_file.id3v2_tag

    ## add/update values
    tag.artist = 'pradeep'
    tag.album = 'programming'

    ## add album art image
    albumart = TagLib::ID3v2::AttachedPictureFrame.new
    albumart.mime_type = "image/png"
    albumart.description = "Media"
    albumart.type = TagLib::ID3v2::AttachedPictureFrame::Media
    albumart.picture = File.open("media.png", 'rb') { |f| f.read }

    tag.add_frame(albumart)

    ## save tags
    mp3_file.save
end



All times are GMT +5.5. The time now is 02:51.