LoginSignup
0
0

More than 3 years have passed since last update.

mp3のタグ(ID3v1)をRubyで読み込む(ライブラリ不使用)

Last updated at Posted at 2021-01-19

ソースコード

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

※拡張子チェックとファイルサイズチェック入れ忘れた・・

所感

久々にRuby書いてみた。

binreadで得られるデータの型が、配列ではなく、ASCII-8BITエンコーディングのstringっていうややこしさよ。
ただ、添え字の書きやすさ・見やすさがイイ。これに慣れるとSubstringとかで切り出すのダルくなりそう。

環境

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

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0