Sound crackles when using the amp method

Hi,

I’m trying to implement a polyphonic synthesizer with polyphonic aftertouch. But when I route the aftertouch events to the amplitude of my sine, it crackles a lot. I guess it’s happening because this method is not intended to be called so often. Here is my synth class:

class PolySynth {
  constructor(num) {
    this.voices = [];
    for(let v = 0; v < num; v++) {
      var env = new p5.Envelope();
      var osc = new p5.Oscillator();
      osc.setType('sine');
      osc.amp(env);
      osc.start();
      this.voices.push([-1,osc,env]);
    }
  }

  noteAttack(pit,vel) {
    var frq = 16.3515*exp(pit*log(2)/12);
    var voi = -1;
    for(let v = 0; v < this.voices.length; v++) {
      var voice = this.voices[v];
      if(voice[0] == pit) {
        voi = v;
        break;
      }
    }
    if(voi == -1) {
      for(let v = 0; v < this.voices.length; v++) {
        var voice = this.voices[v];
        if(voice[0] == -1) {
          voi = v;
          break;
        }
      }
    }
    if(voi >= 0) {
      var voice = this.voices[voi]
      voice[0] = pit;
      voice[1].freq(frq);
      voice[2].set(t1,vel,t2,l2*vel,t3,l3);
      voice[2].triggerAttack();
    }
    else {
      console.log('Maximum number of voices reached.');
    }
  }

  noteAftertouch(pit,vel) {
    for(let v = 0; v < this.voices.length; v++) {
      var voice = this.voices[v];
      if(voice[0] == pit) {
        voice[1].amp(vel);
        break;
      }
    }
  }

  noteRelease(pit) {
    for(let v = 0; v < this.voices.length; v++) {
      var voice = this.voices[v];
      if(voice[0] == pit) {
        voice[0] = -1;
        voice[2].triggerRelease();
        break;
      }
    }
  }
}

Is there a better way to continuously change the amplitude of an audio stream?
Thanks for your time

1 Like