Class: Zappa::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/zappa/generator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sample_rate = 44_100, channels = 2, bit_depth = 16) ⇒ Generator

Returns a new instance of Generator.



5
6
7
8
9
10
# File 'lib/zappa/generator.rb', line 5

def initialize(sample_rate = 44_100, channels = 2, bit_depth = 16)
  @sample_rate = sample_rate
  @channels = channels
  @bit_depth = bit_depth
  @max_amplitude = ((2**bit_depth) / 2) - 1
end

Instance Attribute Details

#bit_depthObject

Returns the value of attribute bit_depth.



3
4
5
# File 'lib/zappa/generator.rb', line 3

def bit_depth
  @bit_depth
end

#channelsObject

Returns the value of attribute channels.



3
4
5
# File 'lib/zappa/generator.rb', line 3

def channels
  @channels
end

#sample_rateObject

Returns the value of attribute sample_rate.



3
4
5
# File 'lib/zappa/generator.rb', line 3

def sample_rate
  @sample_rate
end

Instance Method Details

#generate(type, frequency, length) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/zappa/generator.rb', line 12

def generate(type, frequency, length)
  types = %w(sine square sawtooth white_noise)
  fail "Cannot generate #{type} wave" unless types.include?(type)

  samples = []
  wave_pos = 0.0
  wave_delta = frequency.to_f / @sample_rate.to_f
  num_samples = (length * @sample_rate).round

  num_samples.times do  |i|
    wave_value = send(type, wave_pos)
    abs_value = (wave_value * @max_amplitude).round
    samples[i] = [abs_value] * @channels
    wave_pos += wave_delta
    wave_pos -= 1.0 if wave_pos >= 1.0
    # TODO: - account for skips >= 2.0
  end
  clip_from_samples(samples)
end