Class: Deftones::Source::KarplusStrong

Inherits:
Core::Source show all
Defined in:
lib/deftones/source/karplus_strong.rb

Instance Attribute Summary

Attributes inherited from Core::Source

#mute, #onstop, #volume

Instance Method Summary collapse

Methods inherited from Core::Source

#active_at?, #apply_volume!, #cancel_stop, #clear_transport_event, #dispose, #mute?, #notify_stop_in_window, #number_of_inputs, #render, #render_block, #resolve_time, #resolve_transport_time, #restart, #schedule_transport_event, #source_type, #start, #state, #stop, #sync, #synced?, #unsync, #uses_legacy_render_for_block?

Constructor Details

#initialize(decay: 0.995, damping: 0.5, context: Deftones.context) ⇒ KarplusStrong

Returns a new instance of KarplusStrong.



6
7
8
9
10
11
12
13
# File 'lib/deftones/source/karplus_strong.rb', line 6

def initialize(decay: 0.995, damping: 0.5, context: Deftones.context)
  super(context: context)
  @decay = decay.to_f
  @damping = damping.to_f
  @events = []
  @buffer = []
  @buffer_index = 0
end

Instance Method Details

#consume_events(time) ⇒ Object (private)



41
42
43
44
45
46
47
48
# File 'lib/deftones/source/karplus_strong.rb', line 41

def consume_events(time)
  while @events.any? && @events.first[:time] <= time
    event = @events.shift
    delay_length = [1, (context.sample_rate / event[:frequency]).round].max
    @buffer = Array.new(delay_length) { ((rand * 2.0) - 1.0) * event[:velocity] }
    @buffer_index = 0
  end
end

#process(_input_buffer, num_frames, start_frame, _cache) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/deftones/source/karplus_strong.rb', line 25

def process(_input_buffer, num_frames, start_frame, _cache)
  Array.new(num_frames) do |index|
    time = (start_frame + index).to_f / context.sample_rate
    consume_events(time)
    next 0.0 if @buffer.empty?

    current = @buffer[@buffer_index]
    following = @buffer[(@buffer_index + 1) % @buffer.length]
    @buffer[@buffer_index] = ((current + following) * 0.5 * @decay) + ((following - current) * @damping * 0.01)
    @buffer_index = (@buffer_index + 1) % @buffer.length
    current
  end
end

#trigger(note, time = nil, velocity = 1.0) ⇒ Object



15
16
17
18
19
20
21
22
23
# File 'lib/deftones/source/karplus_strong.rb', line 15

def trigger(note, time = nil, velocity = 1.0)
  @events << {
    time: resolve_time(time),
    frequency: Deftones::Music::Note.to_frequency(note),
    velocity: velocity.to_f
  }
  @events.sort_by! { |event| event[:time] }
  self
end