Skip to content

Language Settings

Note Envelope

An Envelope is a series of fades, defined as time / value pairs. In this example, the envelope will be used to "play" a note by controlling the output amplitude of an oscillator.

The p5.Oscillator sends its output through an internal Web Audio GainNode (p5.Oscillator.output). By default, that node has a constant value of 0.5. It can be reset with the osc.amp() method. Or, in this example, an Envelope takes control of that node, turning the amplitude up and down like a volume knob.

To run this example locally, you will need the p5.sound library and a sound file.

1
2
3
4
5
6
7
8
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
let osc, envelope, fft;
let scaleArray = [60, 62, 64, 65, 67, 69, 71, 72];
let note = 0;
function setup() {
  createCanvas(710, 200);
  osc = new p5.SinOsc();
  // Instantiate the envelope
  envelope = new p5.Env();
  // set attackTime, decayTime, sustainRatio, releaseTime
  envelope.setADSR(0.001, 0.5, 0.1, 0.5);
  // set attackLevel, releaseLevel
  envelope.setRange(1, 0);
  osc.start();
  fft = new p5.FFT();
  noStroke();
}
function draw() {
  background(20);
  if (frameCount % 60 === 0 || frameCount === 1) {
    let midiValue = scaleArray[note];
    let freqValue = midiToFreq(midiValue);
    osc.freq(freqValue);
    envelope.play(osc, 0, 0.1);
    note = (note + 1) % scaleArray.length;
  }
  // plot FFT.analyze() frequency analysis on the canvas
  let spectrum = fft.analyze();
  for (let i = 0; i < spectrum.length / 20; i++) {
    fill(spectrum[i], spectrum[i] / 10, 0);
    let x = map(i, 0, spectrum.length / 20, 0, width);
    let h = map(spectrum[i], 0, 255, 0, height);
    rect(x, height, spectrum.length / 20, -h);
  }
}
X

creative commons license