Question

Using the Web Audio API, I want to use one signal to modulate another. I find the modulation does not behave as expected. The example code below creates two oscillators, one at 440Hz and one at 1Hz, and uses the 1Hz one to modulate the gain of the 440Hz, via the gain AudioParam of a gain node.

Expected behaviour: The oscillators output values from -1 to +1. Therefore, the gain should oscillate between -1 and +1, once per second, i.e. the gain should be zero (no sound) twice per second.

Actual behaviour: Instead, it is only silent once per second. It seems that the gain values are being remapped, so that the range (-1, +1) is mapped to (0, +1).

Questions: Why is this remapping happening? It doesn't happen if I set the gain to single floating point value -- there, +1 means +1 and 0 means 0. Can I turn this remapping off, so that a zero in the modulating signal results in a zero amplitude sound?

Edit: To clarify, my aim is to use an arbitrary envelope, E, whose value varies between 0 and 1, to modulate the amplitude of a carrier, C, so that the output is C*E, such that C*E has amplitude=0 when E=0, and C*E has amplitude=1 when E=1.

window.AudioContext = ( window.AudioContext || window.webkitAudioContext );
var context = new AudioContext();

var gain = context.createGain();
gain.connect(context.destination);

var osc = context.createOscillator();
osc.connect(gain);
osc.start(0);

var mod = context.createOscillator();
mod.frequency.value = 1;
mod.connect(gain.gain);
mod.start(0);
Was it helpful?

Solution

It's not a remapping at all. What is happening is that the gain.value defaults to 1, and the audio-rate signal connected to the gain is being SUMMED with that default value - so the signal is oscillating between (1 - 1) and (1 + 1): that is, between 0 and 2.

Just set gain.gain.value=0; in your example above, and it should work as you expect.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top