RubyQuiz 136 : ID3 Tags

A while back I decided to take on some of the problems from RubyQuiz.  The first one that I picked was the ID3 tags quiz.  My first attempt read in the entire mp3 to get just the last 128 bytes. 

It worked, but really rubbed me the wrong way.  I spent quite a bit of time trying to figure out how to seek to just the bit of  the file that I wanted to read in.  Unfortunately, I didn’t have much luck because I hadn’t used the more low level file IO functions.  In the end, I had to resort to the RubyQuiz solution to figure that out — but it was truly the last resort.  (So what exactly was my input…)

Here is the core of the code:

  # This is the heart of the code for reading the id3 tags.  id3 tags are stored
  #
in the last 128 bytes of the file.
  def read_id3
   
    # When writing this code, this is what caused me the most trouble. 
    #
I didn’t want to have to read in the entire mp3 to get the last 128 bytes.
    #
I knew what I was tring to accomplish, but just couldn’t nail down the .
    #  seek(offset,IO::SEEK_END) on my own.  I ended up finding
    # that code (more or less) on the ruby quiz page — not from lack of

    # searching though.
    offset = -128
    @mp3_file.seek(offset,IO::SEEK_END)
    unparsed_data = @mp3_file.read

   
    # This code is pretty straight forward, after you look at the info on how id3
    #  tags are stored.
    tag, @title, @artist, @album, @year, @comment, genre_index =
               unparsed_data.unpack(’A3A30A30A30A4A30C’)
    @year = @year.to_i
    @genre = @genres[genre_index]
   
  end

The rest of the code, genres file, test code, and a test mp3 are included in the attached zip file.  Do you use autotest?

ID3 Tags Project

Leave a Reply