3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Web Audio APIを使ってブラウザで音を作る

Last updated at Posted at 2025-12-17

はじめに

皆さんはライブコーディングという音楽ジャンルをご存知でしょうか。その名の通り、リアルタイムでコーディングをして音を生成・操作するDJなどに近い音楽ジャンルです。

今回はそのライブコーディングっぽいことをしてみるために、Web Audio APIを使ってブラウザ上で音を再生できる簡単なプログラムを作ってみました。

仕様

playボタンを押すと音が流れ、stopボタンを押すと音が止まるという簡単なプログラムとなっています。

index.html
<!DOCTYPE html>
<html lang="ja">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Web Audio API</title>
    <link rel="stylesheet">
</head>

<body>
    <p>Web Audio APIを使って音を生成</p>
    <button id="play">play</button>
    <button id="stop">stop</button> 
    <script src="./main.js"></script>
</body>

</html>

new AudioContext()でWeb Audio APIを使って音声処理をする基盤となるオブジェクトを作成します。

ctx.createOscillator()で音源の作成、
.type .frequency.setValueAtTime .connectで波形、周波数、出力先を設定し、.start()で音が再生されます。
今回は周波数が17kHzのsine波であるモスキート音を作成します。

main.js
const ctx = new AudioContext();
let oscillator;
let isPlaying = false;

document.getElementById("play").addEventListener("click", function() {
  if (isPlaying) return;
  oscillator = ctx.createOscillator();
  oscillator.type = "sine";
  oscillator.frequency.setValueAtTime(17000, ctx.currentTime);
  oscillator.connect(ctx.destination);
  oscillator.start();
  isPlaying = true;
});

document.getElementById("stop").addEventListener("click", function() {
  oscillator?.stop();
  isPlaying = false;
});

終わりに

今回は単調な音をただ生成するだけのプログラムとなっているので、今後フィルターをかけて音を加工したり、周波数や波形をブラウザ上で変更できる機能を実装してみようかなと思っています。

また、先に説明したライブコーディング専用のプログラミング言語があるらしいのでそちらにも触れてみたいです。

参考サイト

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?