Web Audio API は、Webのオーディオプログラミングを簡素化することを目的とした抽象化レイヤーです。

この短い紹介では、WebAudioAPIについて学習します。 AudioContext、およびの能力 AudioContext ブラウザをレトロシンセサイザーに変換するために使用できるシンプルなオシレーターを作成するためのインスタンス! このチュートリアルのコードスニペットはChromeでテストされていますが、おそらく console お気に入りのブラウザの開発者ツールの

準備作業

前述のように、Web Audio APIのサポートは普遍的ではないため、APIがユーザーのブラウザで使用可能であることを確認することをお勧めします。

let audioContext;

try {
  audioContext =
    new (window.AudioContext || window.webkitAudioContext)();
} catch (error) {
  window.alert(
    `Sorry, but your browser doesn't support the Web Audio API!`
  );
}

if (audioContext !== undefined) {
  /* Our code goes here */
}

この簡単なチェックの後、WebAudioAPIの機能を安全に使用できます。

AudioContextについて

想像するのが役立つかもしれません audioContext–our instance of the AudioContext–as a sort of DJ: it coordinates a collection of audio sources and ensures that the sources play through the user’s speakers at the right time and with the right “sound.” And like a DJ, we can think of audioContext 音源とホストマシンのオーディオハードウェアである「サウンドシステム」との間の仲介役として。 で作業するときに覚えておくべきいくつかの事柄があります AudioContext:

  • The AudioContext マスターの「タイムキーパー」です。 すべての信号は、に関連してスケジュールする必要があります audioContext.currentTime.
  • のインスタンス AudioContext オーディオソースを最初から作成できます。

シンプルなオシレーター

それ自体がどのような音を出すことができるかを知るために、 audioContext を作成するには OscillatorNode:

const oscillator = audioContext.createOscillator();

ブラウザで音を出すために必要なのはこれだけです。 AudioContextOscillatorNode. しかし、最初に、「配線」する必要があります oscillator 私たちに audioContext:

oscillator.connect(audioContext.destination);

Web Audio APIは、アナログシグナルチェーンを模倣しようとします。 入力信号をパイプします( oscillator)デジタルパワーアンプ( audioContext)、次に信号をスピーカーに渡します( destination).

いくつかの音を立てましょう:

oscillator.start();

ダイヤルトーンに匹敵する音が聞こえるはずです。 おめでとうございます。WebAudioAPIを使用して音楽を作成しています。 もちろん、誰も同じピッチを永遠に聞きたくないのです。 あなたは私たちを止めることができます oscillator こちらです:

oscillator.stop();

AudioNodeが停止すると、再開することはできません。 再生を再開するには、新しいAudioNodeを作成する必要があります。

The startstop メソッドは両方ともタイプの単一のパラメーターを受け入れます number. パラメータ値は、開始/停止イベントをスケジュールするために使用されます。

/* Emit a signal 10 seconds from now */
oscillator.start(audioContext.currentTime + 10);

/* Cancel the signal 10 seconds after that */
oscillator.stop(audioContext.currentTime + 20);

私たちの操作によって結論を出しましょう oscillator 別の音を出すために。

AudioParamsでサウンドを操作する

ロギング oscillator オブジェクトの場合、次のようになります(特定のプロパティ値は、デバイス/ブラウザーによって異なる場合があるため、省略されています)。

console.log(oscillator);
/*
  {
    channelCount: number,
    context: AudioContext,
    detune: AudioParam,
    type: 'sine' | 'sawtooth' | 'triangle' | 'square'
    frequency: AudioParam,
    numberOfInputs: number,
    numberOfOutputs: number,
    onended: function
    ...
  }
*/

私たちの目的にとって最も重要な特性は oscillator.frequency:

console.log(oscillator.frequency);
/*
  {
    defaultValue: number,
    maxValue: number,
    minValue: number,
    value: number // Probably 440 (A4)
  }
*/

The frequency 私たちの価値 oscillator を実装します AudioParam インターフェース。 の音 AudioNode そのような oscillator そのを介して操作することができます AudioParam プロパティ。 ただし、 AudioParam value プロパティは廃止され、ヘルパーメソッドが採用されました。

/* Don't do this */
oscillator.frequency.value = 500;

私たちが欲しいなら oscillator 「A」の代わりに「Bb」を放出するには、次のようにする必要があります。

/* The frequency (in Hz) of Bb4 is 466.16 */
oscillator
  .frequency
  .setValueAtTime(466.16, audioContext.currentTime);

また

/* Slowly transition to Bb4 over the span of 10 seconds */
oscillator
  .frequency
  .exponentialRampToValueAtTime(
      466.16,
      audioContext.currentTime + 10
  );

ボーナス:周期波形の調整

私たちの oscillator 周期的な波形を使用してトーンを放出します。 波形は次のように表されます。 type のプロパティ OscillatorNode インターフェース。 デフォルトでは、 type'sine'. ほとんどのブラウザは、少なくとも3つの他のオプションをサポートしています。 'sawtooth', 'triangle'、 と 'square'. だから、私たちの「トーン」を変える oscillator と同じくらい簡単です:

oscillator.type = 'triangle';

結論

Web Audio APIのおかげで、ブラウザでのオーディオの生成と操作がこれまでになく簡単になりました。 その助けを借りて、Web開発者は3〜5行のコードでレトロなシンセトーンを再現できます。

🎶課題:Web Audio APIを使用して、 Funkytown からリフをプログラムしてください!