Published
Edited
Nov 3, 2021
Insert cell
# 02 play mp3 buffer
## Frontend masters [Web-Audio by Matt DesLauriers](https://github.com/mattdesl/workshop-web-audio)

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

Insert cell
function loadSound() {
// Re-use the same context if it exists
if (!audioContext) {
mutable audioContext = new AudioContext();
}

// Re-use the audio buffer as a source
if (!audioBuffer) {

mutable audioBuffer = audioContext.decodeAudioData(audioFile);
}
}
Insert cell
audioFile = FileAttachment("chime.mp3").arrayBuffer()
Insert cell
function playSound() {
// Ensure we are all loaded up
loadSound();

// Ensure we are in a resumed state
audioContext.resume();

// Now create a new "Buffer Source" node for playing AudioBuffers
const source = audioContext.createBufferSource();

// Connect to destination
source.connect(audioContext.destination);

// Assign the loaded buffer
source.buffer = audioBuffer;

// Start (zero = play immediately)
source.start(0);
}
Insert cell
p5(sketch => {
sketch.setup = function() {
sketch.createCanvas(width, width/2);
};
sketch.draw = function() {
sketch.background("#001b42");
sketch.fill("white");
sketch.noStroke();

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

}

sketch.mousePressed = function () { // play sound if any place on the screen
playSound();
}

// 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
mutable audioContext = null

Insert cell
mutable audioBuffer = null
Insert cell
height = width/2
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