Class: Mml2wav::Wave

Inherits:
Object
  • Object
show all
Extended by:
WaveFile
Defined in:
lib/mml2wav/wave.rb

Class Method Summary collapse

Class Method Details

.write(sounds, options = {}) ⇒ Object



9
10
11
12
13
14
15
16
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
# File 'lib/mml2wav/wave.rb', line 9

def write(sounds, options={})
  output_path = options[:output] || "doremi.wav"
  sampling_rate = options[:sampling_rate] || 22050
  bpm = options[:bpm] || 120
  velocity = 5
  octave = 4
  default_length = 4.0

  format = Format.new(:mono, :pcm_8, sampling_rate)
  Writer.new(output_path, format) do |writer|
    buffer_format = Format.new(:mono, :float, sampling_rate)
    sounds.scan(/T\d+|V\d+|L\d+|[A-G][#+-]?\d*\.?|O\d+|[><]|./i).each do |sound|
      base_sec = 60.0 * 4
      length = default_length
      case sound
      when /\AT(\d+)/i
        bpm = $1.to_i
      when /\AV(\d+)/i
        velocity = $1.to_i
      when /\AL(\d+)/i
        default_length = $1.to_f
      when /\A([A-G][#+-]?)(\d+)(\.)?/i
        length = $2.to_f
        sound = $1
        length = default_length / 1.5 if $3
      when /\AO(\d+)/i
        octave = $1.to_i
      when "<"
        octave += 1
      when ">"
        octave -= 1
      end
      sec = base_sec / length / bpm
      amplitude = velocity.to_f / 10
      frequency = Scale::FREQUENCIES[sound.downcase]
      next unless frequency
      frequency *= (2 ** octave)
      samples = sine_wave(frequency, sampling_rate, sec, amplitude)
      buffer = Buffer.new(samples, buffer_format)
      writer.write(buffer)
    end
  end
end