Class: SynthBlocks::Mod::Adsr

Inherits:
Object
  • Object
show all
Defined in:
lib/synth_blocks/mod/adsr.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attack, decay, sustain, release) ⇒ Adsr

Creates new ADSR envelope

attack, decay and release are times in seconds (as float)

sustain should be between 0 and 1



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/synth_blocks/mod/adsr.rb', line 25

def initialize(attack, decay, sustain, release)
  @value = 0
  @start_time = 0
  @last_t = 0
  @done = false
  @start_value = 0
  @attack = attack
  @decay = decay
  @sustain = sustain
  @release = release
end

Instance Attribute Details

#attackObject

attack time in seconds



6
7
8
# File 'lib/synth_blocks/mod/adsr.rb', line 6

def attack
  @attack
end

#decayObject

decay time in seconds



10
11
12
# File 'lib/synth_blocks/mod/adsr.rb', line 10

def decay
  @decay
end

#releaseObject

release time in seconds



17
18
19
# File 'lib/synth_blocks/mod/adsr.rb', line 17

def release
  @release
end

#sustainObject

sustain level (0.0-1.0)



13
14
15
# File 'lib/synth_blocks/mod/adsr.rb', line 13

def sustain
  @sustain
end

Instance Method Details

#run(t, released) ⇒ Object

run the envelope.

if released is given (should be <= t), the envelope will enter the release stage returns the current value between 0 and 1



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/synth_blocks/mod/adsr.rb', line 42

def run(t, released)
  delta = t - @last_t
  @last_t = t
  if released
    return 0 if @done
    @value += -(@sustain/@release) * (delta)
    if @value <= 0
      @value = 0
      @done = true
    end
    return @value
  else
    if t < 0.0001 # initialize start value (slightly hacky, but works)
      @start_time = t
      return @value
    end
    if t <= @attack
      return @value += 1/@attack * delta
    elsif t <= @attack + @decay
      return @value += -(1-@sustain)/@decay * delta
    else
      return @value = @sustain
    end
  end 
  @a_s = 1 / @attack
end