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.
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 inputs | 1 |
| Number of outputs | 1 |
| Channel count | 2 |
| Channel count mode | max |
| Channel interpretation | speakers |
Constructor
constructor(context: BaseAudioContext, options?: GainOptions)
GainOptions
Inherits all properties from AudioNodeOptions
| Parameter | Type | Default | |
|---|---|---|---|
gain Optional | number | 1.0 | Initial 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.
| Name | Type | Description | |
|---|---|---|---|
gain | AudioParam | a-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.0amplify the signal; values between0and1.0attenuate it. - A value of
0silences 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.