Search code examples
javascriptweb-audio-api

How to make a function for create oscillatorNodes using Web Audio Api


I know this sounds kind of easy or obvious but I can't make this work.

See this snippet:

ctx = new AudioContext();
gain = ctx.createGain();
gain.connect(ctx.destination);
gain.gain.value = 0.5;


osc1 = ctx.createOscillator();
osc1.connect(gain);
osc1.frequency.value = 450;
osc1.start();
osc1.stop(2);

osc2 = ctx.createOscillator();
osc2.connect(gain);
osc2.frequency.value = 500;
osc2.start();
osc2.stop(2);
console.log("playing");

It plays two Oscillators at the time without problems but it repeats code. If I try to put the redundant code in a function it does not work.

ctx = new AudioContext();
gain = ctx.createGain();
createAndPlayOsc(450);
createAndPlayOsc(500);


function createAndPlayOsc(freq){
    console.log("creating osc with freq " + freq);
    var osc = ctx.createOscillator();
    osc.connect(gain);
    osc.frequency.value = freq;
    osc.start();
    osc.stop(2);
    console.log("playing osc with freq " + freq);
}

Even if I send the AudioContext

ctx = new AudioContext();
gain = ctx.createGain();
createAndPlayOsc(450, ctx);
createAndPlayOsc(500, ctx);


function createAndPlayOsc(freq, context){
    console.log("creating osc with freq " + freq);
    var osc = context.createOscillator();
    osc.connect(gain);
    osc.frequency.value = freq;
    osc.start();
    osc.stop(2);
    console.log("playing osc with freq " + freq);
}

or Both the gainNode and context

ctx = new AudioContext();
gain = ctx.createGain();
createAndPlayOsc(450, ctx, gain);
createAndPlayOsc(500, ctx, gain);


function createAndPlayOsc(freq, context, gainNode){
    console.log("creating osc with freq " + freq);
    var osc = context.createOscillator();
    osc.connect(gainNode);
    osc.frequency.value = freq;
    osc.start();
    osc.stop(2);
    console.log("playing osc with freq " + freq);
}

What I am missing?


Solution

  • You forgot to connect the gain to the context:

    gain.connect(ctx.destination);