How to change volume when using setADSR

In this sketch, typing key produces tones at different pitches and the slider changes the volume

Neither of the examples https://p5js.org/reference/#/p5.Envelope and https://p5js.org/examples/sound-note-envelope.html allow changing the sound volume. This example show how it can be done. The secret to use setADSR() just before triggerAttack() or play().

This example uses the code
  envelope = new p5.Env();
  envelope.setADSR(attackTime, decayTime, vol, releaseTime);
  envelope.setRange(attackLevel, releaseLevel);
in setup() and
  midi = interpretCh(key); // midi value associated with key pressed
  osc.freq(midiToFreq(midi));
  envelope.setADSR(attackTime, decayTime, vol, releaseTime);
  envelope.triggerAttack();

in keyTyped() where
  vol = volSlider.value()/100;
is in draw( ) to keep vol up to date. Slider goes from 0 to 100 so vol goes from 0 to 1.

Changing the slider while the tone is playing does not change the volume of the sound. The current value of the slider is used every time a key is pressed to sound a note.

That leads to an interesting question. If I were to move the setADSR call to the draw function, would it allow me to change the volume whenever the slider was moved? Unfortunately, the answer appears to be "no". I haven't read the code for p5.Envelope. but experimentation indicates that a number of calculations are done and the envelope fixed when one calls triggerAttack() and the envelope can't be changed until the sound is triggered again.

p5.js source code: HowToSetADSR.pjs

James Brink,     2/7/2020