Read mp3 tag (ID3v1) in Ruby (no library used)

Source code

mp3tagID3V1read.rb



#!/usr/bin/ruby

if ARGV.size() == 0 then
  print "need an argument."
else
  if File.exist?(ARGV[0]) then
    stat = File.stat(ARGV[0])
    a = File.binread(ARGV[0], 128, stat.size-128)
    
    if (a[0..2]=="TAG") then
      title   = a[ 3..32].force_encoding("Shift_JIS").rstrip
      artist  = a[33..62].force_encoding("Shift_JIS").rstrip
      album   = a[63..92].force_encoding("Shift_JIS").rstrip
      yearStr = a[93..96].rstrip
      trackMark = a[125]
      genreNo = a[127]

      if trackMark == "\0" then
        # track info exists
        comment = a[97..124].force_encoding("Shift_JIS").rstrip
        trackNo = (a[126].bytes)[0].to_s
      else
        comment = a[97..126].force_encoding("Shift_JIS").rstrip
        trackNo = ""
      end

      print "track : <" + trackNo + ">\n"
      print "album : <" + album   + ">\n"
      print "artist: <" + artist  + ">\n"
      print "title : <" + title   + ">\n"
      print "year  : <" + yearStr + ">\n"
      print "comment: <" + comment +">\n"
    end
  end
end

Impressions

I wrote Ruby after a long time.

The type of data obtained by binread is not an array, but ASCII-8BIT encoding string, which is complicated. However, the ease of writing and viewing the subscripts is good. If you get used to this, it will become dull to cut out with Substring.

environment

OS : Windows 10 Ruby 2.6.5 (C:\Ruby26-x64\bin\ruby.exe)

reference

-IO.binread (Ruby 3.0.0 Reference Manual) -String # force_encoding (Ruby 3.0.0 Reference Manual) -String # bytes (Ruby 3.0.0 Reference Manual) --Read mp3 tags (ID3v1, ID3v2) (no library used) --Qiita

Recommended Posts

Read mp3 tag (ID3v1) in Ruby (no library used)
Read design patterns in Ruby
A memorial service for the library used when competing in Ruby
Is there no type in Ruby?
Ruby methods often used in Rails
I made a Ruby extension library in C
About regular expressions used in ruby sub method