| sidebar_position | 3 |
|---|
import AudioNodePropsTable from "@site/src/components/AudioNodePropsTable" import { Optional, ReadOnly } from '@site/src/components/Badges';
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.
:::
constructor(context: BaseAudioContext, options?: GainOptions)Inherits all properties from AudioNodeOptions
| Parameter | Type | Default | |
|---|---|---|---|
gain |
number |
1.0 |
Initial value for gain |
You can also create a GainNode via the BaseAudioContext.createGain() factory method, which uses default values.
It inherits all properties from AudioNode.
| Name | Type | Description | |
|---|---|---|---|
gain |
AudioParam |
a-rate AudioParam representing the gain value to apply. |
GainNode does not define any additional methods.
It inherits all methods from AudioNode.
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);- 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.
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.