How to loop sound generated within a p5 envelope

Thank you for your comments kll. Please allow me to better explain what I am trying to do, that is, to repeat the oscillator-generated/envelope-packaged sound multiple times after a single click. I tried inserting loop() and that failed (see commented out section). I tried writing a short loop with a counter and all that did was cap the number of click-generated sounds. I believe that the loop() function works with a loaded sound file but am hoping to get the same result with sound created by the oscillator. Once again, grateful for the suggestions from you and the community.

let attackLevel = 1.0;
let releaseLevel = 0;
let attackTime = 0.001;
let decayTime = 0.2;
let susPercent = 0.2;
let releaseTime = 0.5;

let env, triOsc;
let t = 0;

function setup() {
  let cnv = createCanvas(100, 100);

  textAlign(CENTER);
  text('click to play', width / 2, height / 2);

  env = new p5.Envelope();
  env.setADSR(attackTime, decayTime, susPercent, releaseTime);
  env.setRange(attackLevel, releaseLevel);

  triOsc = new p5.Oscillator('triangle');
  triOsc.amp(env);
  triOsc.start();
  triOsc.freq(220);

  cnv.mousePressed(playEnv);
}

/*
function playEnv() {
    env.play(triOsc);
    loop()
}
*/

function playEnv() {
  if (t < 3) {
    env.play(triOsc);
    t = t + 1;
    print(t);
  }
}
1 Like