Published
Edited
Jun 7, 2022
1 fork
Insert cell
# 10 tone demo

## Frontend masters [Web-Audio by Matt DesLauriers](https://github.com/mattdesl/workshop-web-audio) (tone.js)

[Replay only available as editing still happening](https://frontendmasters.com/workshops/web-audio/).



Insert cell
volume = -15
Insert cell
Tone.Master.volume.value = volume;
Insert cell
https://tonejs.github.io/docs/r13/Synth
https://tonejs.github.io/docs/r13/Oscillator
[Types of Oscillator.](https://tonejs.github.io/docs/r13/Oscillator#:~:text=%3C/%3E-,.type,-%E2%86%9D%20String%20%23)
Insert cell
synth = new Tone.Synth({
oscillator: {
type: "triangle", // sine, square, triangle, sawtooth
},
}).toDestination() // skips synth.connect(Tone.Master);
Insert cell
p5(sketch => {
sketch.setup = function() {
sketch.createCanvas(width,height);
};
sketch.draw = function() {
sketch.background("#001b42");
sketch.fill("white");
sketch.noStroke();

// Draw play/pause button
const dim = sketch.min(width, height);
if (!sketch.mouseIsPressed) polygon(width / 2, height / 2, dim * 0.1, 3);

// Get a 0..1 value for the mouse
const u = sketch.max(0, sketch.min(1, sketch.mouseX / width));

// Choose a frequency that sounds good
const frequency = sketch.lerp(75, 2500, u);
synth.setNote(frequency);

if (sketch.mouseIsPressed) {
const time = sketch.millis() / 1000;

const verts = 1000;
sketch.noFill();
sketch.stroke('yellow');
sketch.strokeWeight(dim * 0.005);
sketch.beginShape();
for (let i = 0; i < verts; i++) {
const t = verts <= 1 ? 0.5 : i / (verts - 1);
const x = t * width;
let y = height / 2;

// This is not an accurate representation, but
// instead exaggerated for the sake of visualization
const frequencyMod = sketch.lerp(1, 1000, sketch.pow(u, 5));
const amplitude = sketch.sin(time + t * frequencyMod);

y += (amplitude * height) / 2;

sketch.vertex(x, y);
}
sketch.endShape();
}
}

// Update the FX and trigger synth ON
sketch.mousePressed = function () {
synth.triggerAttack();
}

// Trigger synth OFF
sketch.mouseReleased = function () {
synth.triggerRelease();
}

// Draw a basic polygon, handles triangles, squares, pentagons, etc
function polygon(x, y, radius, sides = 3, angle = 0) {
sketch.beginShape();
for (let i = 0; i < sides; i++) {
const a = angle + sketch.TWO_PI * (i / sides);
let sx = x + sketch.cos(a) * radius;
let sy = y + sketch.sin(a) * radius;
sketch.vertex(sx, sy);
}
sketch.endShape(sketch.CLOSE);
}
})
Insert cell
height = width/3
Insert cell
Tone = require('tone')
Insert cell
import {p5} from "@tmcw/p5"
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more