beep音再生をクラス化してみる。

require 'beep'
# ↓きらきら星の歌。
p1 = Beep.new 'ドドソソララソーファファミミレレドー'
p2 = Beep.new 'ソソファファミミレー'
p1.play;p2.play;p2.play;p1.play

とかして再生したりできる様に。

#!/usr/bin/ruby -Ks
# -*- coding: shift_jis -*-
require 'Win32API'
class Beep
  @@F = {}
  @@Api = Win32API.new('kernel32', "Beep",'LL',"L")
  a = 'ラ.シド.レ.ミファソ.ラ.シど.れ.みふぁそぞら.し'.split(//)
  a.each_index{|i| @@F[a[i]] = (2**(i/12.0)*220.0).round }
  @@duration = 150 # 標準的な音の長さを 150ms にしておく(てきとー)
  def initialize(music_string = nil)
    @seq = Beep.str_to_seq(music_string) if music_string
  end
  def Beep.str_to_seq(music_string)
    music_string.gsub!(/[ァぁ]/,'')
    duration = @@duration
    seq = []
    music_string.split(//).reverse.each do |f|
      if // =~ f
        duration += @@duration
      else
        seq.unshift([@@F[f],duration]) 
        duration = @@duration
      end
    end
    seq
  end
  def Beep.play(seq = [])
    if seq.class == String
      seq = str_to_seq(seq)
    end
    seq.each do |s| 
      if s[0]
        @@Api.call(*s)
      else
        sleep s[1]/1000.0
      end
    end
  end
  def play(seq = @seq)
    Beep.play seq
  end
end
if $0 == __FILE__
  music = ARGV.size>0 ? IO.read(ARGV[0]) : 'ソどみそ,みそーー'
  Beep.play music # スタジアムで流れる「パラララッパラー♪」↑てやつ。
end