Skip to main content

GainNode

The GainNode interface represents a change in volume (amplitude) of the audio signal. It is an AudioNode with a single gain AudioParam that multiplies every sample passing through it.

tip

Direct, immediate gain changes often cause audible clicks. Use the scheduling methods of AudioParam (e.g. linearRampToValueAtTime, exponentialRampToValueAtTime) to smoothly interpolate volume transitions.

AudioNode properties

Number of inputs1
Number of outputs1
Channel count2
Channel count modemax
Channel interpretationspeakers

Constructor

constructor(context: BaseAudioContext, options?: GainOptions)

GainOptions

Inherits all properties from AudioNodeOptions

ParameterTypeDefault
gain
Optional
number1.0Initial value for gain

You can also create a GainNode via the BaseAudioContext.createGain() factory method, which uses default values.

Properties

It inherits all properties from AudioNode.

NameTypeDescription
gainAudioParama-rate AudioParam representing the gain value to apply.
Read only

Methods

GainNode does not define any additional methods. It inherits all methods from AudioNode.

Usage

A common use case is controlling the master volume of an audio graph:

const audioContext = new AudioContext();
const gainNode = audioContext.createGain();

// Set volume to 50%
gainNode.gain.setValueAtTime(0.5, audioContext.currentTime);

// Connect source → gain → output
source.connect(gainNode);
gainNode.connect(audioContext.destination);

To fade in a sound over 2 seconds:

gainNode.gain.setValueAtTime(0, audioContext.currentTime);
gainNode.gain.linearRampToValueAtTime(1, audioContext.currentTime + 2);

Remarks

gain

  • Nominal range is -∞ to ∞.
  • Values greater than 1.0 amplify the signal; values between 0 and 1.0 attenuate it.
  • A value of 0 silences the signal. Negative values invert the signal phase.

Advanced usage — Envelope (ADSR)

GainNode is the key building block for implementing sound envelopes. For a practical, step-by-step walkthrough of ADSR envelopes and how to apply them in a real app, see the Making a piano keyboard guide.