Search code examples
javascriptsignal-processingweb-audio-apip5.js

Dynamically setPeriodicWave() of WebAudio Oscillator that's playing?


Trying to do some basic wavetable synthesis (developing an addon for p5.sound) – and wondering if it's possible to dynamically change the waveform of an oscillator while it's playing (constant tone rather than note duration)? In my basic testing, the setPeriodicWave() function has to be called before the oscillator is connected to the AudioContext output then started. Hoping to do some dynamic wavetable synth (with two hard panned channels) for feeding into the X-Y mode of an oscilloscope (for vector visuals based on audio signals). The workflow above, constantly creating a new oscillator with every wavetable change, causes lots of artifacts and phase-shifting issues... it would be great if I could start two oscillators and just update their waveform. Any tips on workflow for doing so? My abstracted workflow:

  • create oscillator with 'custom' type (inited with a flat/silent wave)
  • custom setWavetable() which uses functions from dsp.js to createPeriodicWave() with array values
  • re-init oscillator with this wave (stop oscil, disconnect/trash oscil, init new oscil w/ wave, connect + start oscil)

Solution

  • What issues are you having? As an example, this works for me. I can clearly hear the sound change:

    let c = new AudioContext();
    let s = new OscillatorNode(c, {type: "sawtooth"});
    s.connect(c.destination);
    // Some random custom wave form
    let w = new PeriodicWave(c, {real: [0, 1], imag: [0, 1]});
    s.start();
    // Wait a bit
    s.setPeriodicWave(w);
    // Sound changes