Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

GainNode — controlling audio amplitude

GainNode multiplies audio samples by the gain parameter, enabling muting, amplification, and amplitude automation.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

const node = new GainNode(context, { gain: 0.5 });
// Alternative:
const node2 = context.createGain();
node2.gain.value = 0.5;

GainNode is a Web Audio API node with one input and one output. It multiplies every sample of every channel by gain: 1 preserves amplitude, 0 mutes, and a negative value inverts polarity. The multiplier is linear, not measured in decibels.

gain is an AudioParam object, defaulting to 1 with a-rate automation. Change gain.value, rather than assigning a number to gain. For smooth transitions, use methods such as gain.linearRampToValueAtTime(value, time); abrupt changes can cause clicks.

This is a browser API, not part of ECMAScript; having Node.js does not establish its availability.

Examples

(async () => {
  const context = new OfflineAudioContext(1, 128, 48000);
  const buffer = context.createBuffer(1, 128, 48000);
  buffer.getChannelData(0).set([0.5, -0.5, 1, -1]);

  const source = context.createBufferSource();
  source.buffer = buffer;
  const gain = new GainNode(context, { gain: 0.25 });
  source.connect(gain).connect(context.destination);
  source.start(0);

  const rendered = await context.startRendering();
  console.log(JSON.stringify(
    Array.from(rendered.getChannelData(0).slice(0, 4))
  ));
})();

Result

[0.125,-0.125,0.25,-0.25]

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources