Skip to content

Latest commit

 

History

History
79 lines (52 loc) · 2.83 KB

File metadata and controls

79 lines (52 loc) · 2.83 KB
sidebar_position 3

import AudioNodePropsTable from "@site/src/components/AudioNodePropsTable" import { Optional, ReadOnly } from '@site/src/components/Badges';

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. :::

Constructor

constructor(context: BaseAudioContext, options?: GainOptions)

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.

Properties

It inherits all properties from AudioNode.

Name Type Description
gain AudioParam a-rate AudioParam representing the gain value to apply.

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.