0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

p5.js Web Editor上で Tone.js を使って音を鳴らす【その1】

Last updated at Posted at 2021-11-21

タイトル通りの内容です。
Tone.js のページに書いてある以下の内容を、p5.js Web Editor上でまとめて試せるものを作ってみました。

  • Hello Tone
  • Tone.Synth
  • triggerAttackRelease
  • Instruments
  • Samples

ライブラリの読み込み

まず、index.html の中で以下を指定し、CDN上のライブラリを読み込ませました。

<script src="https://cdnjs.cloudflare.com/ajax/libs/tone/14.8.32/Tone.min.js"></script>

JavaScript のプログラム

そして、sketch.js の内容は、以下のようにしてみました。

let player,
  synth = [];

function preload() {
  player = new Tone.Player(
    "https://tonejs.github.io/audio/berklee/gong_1.mp3"
  ).toDestination();
}

function setup() {
  createCanvas(400, 400);
  background(220);

  synth.push(new Tone.AMSynth().toDestination());
  synth.push(new Tone.Synth().toDestination());
  synth.push(new Tone.FMSynth().toDestination());
  synth.push(new Tone.PolySynth(Tone.Synth).toDestination());
}

function draw() {}

function keyPressed() {
  let synthTemp;
  const now = Tone.now();
  switch (key) {
    case "a":
      synthTemp = synth[0];
      synthTemp.triggerAttackRelease("C4", "8n");
      break;
    case "s":
      synthTemp = synth[1];
      synthTemp.triggerAttack("C4", now);
      synthTemp.triggerRelease(now + 1);
      break;
    case "d":
      synthTemp = synth[2];
      synthTemp.triggerAttackRelease("C4", "8n", now);
      synthTemp.triggerAttackRelease("E4", "8n", now + 0.5);
      synthTemp.triggerAttackRelease("G4", "8n", now + 1);
      break;
    case "f":
      synthTemp = synth[3];
      synthTemp.triggerAttack("D4", now);
      synthTemp.triggerAttack("F4", now + 0.5);
      synthTemp.triggerAttack("A4", now + 1);
      synthTemp.triggerAttack("C5", now + 1.5);
      synthTemp.triggerAttack("E5", now + 2);
      synthTemp.triggerRelease(["D4", "F4", "A4", "C5", "E5"], now + 4);
      break;
    case "g":
      player.start();
      break;
  }
}

あとはプログラムを実行し、「a/s/d/f/g」の 5つのキーのうちのどれかを押下すると、それぞれ異なる音を鳴らすことができます。

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?