Class: Rhythmmml::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/rhythmmml/parser.rb

Instance Method Summary collapse

Constructor Details

#initialize(sounds, sampling_rate, options = {}) ⇒ Parser

Returns a new instance of Parser.



5
6
7
8
9
10
11
12
13
14
15
# File 'lib/rhythmmml/parser.rb', line 5

def initialize(sounds, sampling_rate, options={})
  pattern = /T\d+|V\d+|L\d+|[A-GR][#+-]?\d*\.?|O\d+|[><]|./i
  @sounds = sounds.scan(pattern)
  @sampling_rate = sampling_rate
  @bpm = options[:bpm] || 120
  @velocity = options[:velocity] || 5
  @octave = options[:octave] || 4
  @default_length = options[:default_length] || 4.0
  @octave_reverse = options[:octave_reverse] || false
  @cursor = 0
end

Instance Method Details

#parseObject



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/rhythmmml/parser.rb', line 17

def parse
  rhythm_infos = []
  @cursor.upto(@sounds.size - 1) do |i|
    sound = @sounds[i]
    base_sec = 60.0 * 4
    length = @default_length
    case sound
    when /\AT(\d+)/i
      @bpm = $1.to_i
      next
    when /\AV(\d+)/i
      @velocity = $1.to_i
      next
    when /\AL(\d+)/i
      @default_length = $1.to_f
      next
    when /\A([A-GR][#+-]?)(\d+)(\.)?/i
      length = $2.to_f
      sound = $1
      length = @default_length / 1.5 if $3
    when /\AO(\d+)/i
      @octave = $1.to_i
      next
    when "<"
      @octave += @octave_reverse ? -1 : 1
      next
    when ">"
      @octave -= @octave_reverse ? -1 : 1
      next
    end
    sec = base_sec / length / @bpm
    amplitude = @velocity.to_f / 10
    frequency = Mml2wav::Scale::FREQUENCIES[sound.downcase]
    next unless frequency
    frequency *= (2 ** @octave)
    rhythm_infos << [sound.downcase, sec, [frequency, @sampling_rate, sec, amplitude]]
    @cursor = i + 1
  end
  rhythm_infos
end