BaseAudioContext: createGain() メソッド

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2021.

createGain()BaseAudioContext インターフェイスのメソッドで、 GainNode を生成します。これは、音声グラフの全体的なゲイン(音量)を調整するのに使用します。

メモ: GainNode() コンストラクターは GainNode を作成するための推奨される方法です。 AudioNode の作成を参照してください。

構文

js
createGain()

引数

なし。

返値

1 つ以上の音声ソースを入力とし、ノードの GainNode で指定されたレベルにゲイン(音量)が調整された音声を出力する GainNode.gain です。 a-rate 引数で指定された音量にゲイン調整された音声を出力します。

次の例は AudioContext を使って GainNode を作成し、Mute ボタンをクリックしたときに gain プロパティの値を変更して音声をミュートしたりミュート解除したりする基本的な使用方法を示しています。

以下のスニペットはそのままでは動作しません。完全な動作例については、 Voice-change-O-maticソースを閲覧)デモをご覧ください。

html
<div>
  <button class="mute">Mute button</button>
</div>
js
const audioCtx = new AudioContext();
const gainNode = audioCtx.createGain();
const mute = document.querySelector(".mute");
let source;

if (navigator.mediaDevices.getUserMedia) {
  navigator.mediaDevices.getUserMedia(
    // constraints - only audio needed for this app
    {
      audio: true,
    },

    // Success callback
    (stream) => {
      source = audioCtx.createMediaStreamSource(stream);
    },

    // Error callback
    (err) => {
      console.error(`The following gUM error occurred: ${err}`);
    },
  );
} else {
  console.error("getUserMedia not supported on your browser!");
}

source.connect(gainNode);
gainNode.connect(audioCtx.destination);

// …

mute.onclick = () => {
  if (mute.id === "") {
    // 0 means mute. If you still hear something, make sure you haven't
    // connected your source into the output in addition to using the GainNode.
    gainNode.gain.setValueAtTime(0, audioCtx.currentTime);
    mute.id = "activated";
    mute.textContent = "Unmute";
  } else {
    gainNode.gain.setValueAtTime(1, audioCtx.currentTime);
    mute.id = "";
    mute.textContent = "Mute";
  }
};

仕様書

Specification
Web Audio API
# dom-baseaudiocontext-creategain

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
createGain

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

関連情報