-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjavascript-audio.html
351 lines (281 loc) · 8.3 KB
/
javascript-audio.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Making sounds in JavaScript</title>
<meta name="description" content="An elementary introduction to JavaScript audio">
<style>
:root {
--border-code: #7df9ff;
}
body {
margin: 4em 2em;
line-height: 1.5;
max-width: 40em;
}
@media (width < 40em) {
body {
margin: 1em 0em;
}
}
body {
margin-block-end: 5em;
}
@media (prefers-color-scheme: dark) {
body {
background-color: oklch(31.14% 0.021 285.75);
color: oklch(90% 0.008 286.75);
}
a {
color: #a2cffe;
}
a:visited {
color: #ca9bf7;
}
}
h2, h3, p, ol {
margin-inline: 3rem;
}
p, li {
margin-block: 2.25em;
}
h3 {
margin-block-start: 5rem;
}
h2 + h3 {
margin-block-start: 2.25rem;
}
ol {
padding-inline-start: 1em;
}
li {
padding-inline-start: 1ch;
}
pre {
margin-inline: 1rem;
padding: 2.5rem;
border: 1px solid var(--border-code);
overflow-x: auto;
}
@media (width < 40em) {
h2, h3, p, ol {
margin-inline: 1rem;
}
pre {
margin-inline: 0;
padding-inline: 1rem;
border-inline: 0;
}
}
blockquote {
border-inline-start: 2px solid #bbb;
margin-inline-start: 1rem;
margin-block: 3rem;
opacity: 0.8;
}
blockquote p {
margin-block: 1.5rem;
margin-inline-start: 2rem;
}
@media (width < 40em) {
blockquote p {
margin-inline-start: 1rem;
}
}
button {
cursor: pointer;
background-color: transparent;
padding: 1ch 2ch;
font-size: 1rem;
min-width: 5rem;
border: 1px solid var(--border-code);
color: inherit;
border-radius: 3px;
}
.playing {
border-color: tomato;
}
</style>
<script type="module">
import { toggleFirstTone, beep } from "./js/javascript-audio.ts";
const togglePlaying = (cls, cond) =>
Array.from(document.getElementsByClassName(cls)).forEach((e) =>
cond ? e.classList.add("playing") : e.classList.remove("playing"),
);
let osc1;
document.querySelector("button.demo-1").addEventListener("click", () => {
osc1 = toggleFirstTone(osc1);
togglePlaying("demo-1", osc1);
})
let osc2s = new Set();
document.querySelector("button.demo-2").addEventListener("click", () => {
togglePlaying("demo-2", true);
const osc = beep(0.2);
osc2s.add(osc);
osc.onended = () => {
osc2s.delete(osc);
togglePlaying("demo-2", osc2s.size > 0);
};
})
const toggleBeeps = (id) =>
id ? (clearInterval(id), undefined) : setInterval(() => beep(0.01), 1000 / 7);
let intervalId;
document.querySelector("button.demo-3").addEventListener("click", () => {
intervalId = toggleBeeps(intervalId);
togglePlaying("demo-3", intervalId);
})
</script>
</head>
<body>
<h2>Making sounds in JavaScript</h2>
<h3>First sound</h3>
<p>
Let's make a sound in JavaScript. Browsers implement WebAudio. WebAudio provides
two ways of making sounds:
</p>
<ol>
<li>
The simpler way is by connecting a collection of primitive nodes that WebAudio
provides - these are things like oscillators, barebones IIR filters etc.
</li>
<li>
The more advanced way is to use a thing called "AudioWorklet", wherein we write
code to compute the individual samples themselves.
</li>
</ol>
<p>Let's make a sound using the first method.</p>
<pre class="demo-1"><code>const ctx = new AudioContext();
ctx.resume();
const osc = new OscillatorNode(ctx);
// Reduce volume, the default is too loud!
const mix = new GainNode(ctx, { gain: 0.1 });
osc.connect(mix).connect(ctx.destination);
osc.start();
</code></pre>
<p>
<button class="demo-1">Play / Pause</button>
<br><br>That is what the button above does.
</p>
<h3>Beep</h3>
<p>
When you toggle the button above, you'd notice a glitch when the sound starts
and stops.
</p>
<p>
Our ears are more sensitive than you might consciously imagine. When we start
the sound above, it immediately starts playing, and this sudden movement is
heard as a rather ugly pop. Ditto when the sound immediately stops.
</p>
<p>
Real life sounds don't behave like that. They have an <em>attack</em> phase,
when the sound slowly rises from nothing (say if you hit a drum with a stick).
And there is a <em>release</em> phase where the sound slowly dies away instead
of suddenly stopping.
</p>
<p>Let's add them to our sound. And also move it to a function.</p>
<pre class="demo-2"><code>const beep = (duration) => {
const attack = 0.001; // Attack of 1 ms
const release = 0.1; // Release of 100 ms
const t = ctx.currentTime;
const osc = new OscillatorNode(ctx);
const env = new GainNode(ctx);
env.gain.setValueCurveAtTime([0, 1], t, attack);
env.gain.setTargetAtTime(0, t + attack + duration, release / 5);
const mix = new GainNode(ctx, { gain: 0.1 });
osc.connect(env).connect(mix).connect(ctx.destination);
osc.start();
osc.stop(t + attack + duration + release);
};
</code></pre>
<p><button class="demo-2">Beep</button></p>
<h3>Beeps</h3>
<p>
Instead of clicking the button ourselves, let us ask the computer to click it
for us, 7 times every second.
</p>
<pre class="demo-3"><code>setInterval(() => {
beep(0.01);
}, 1000 / 7);
</code></pre>
<p><button class="demo-3">Beeps</button></p>
<blockquote>
<p><em>Why 7?</em></p>
<p>
In music, a second is like an eternity. Events in music happen at the time scale
of milliseconds, and there are a <em>thousand</em> milliseconds in a second.
</p>
<p>
However, something interesting happens at around 20 to 50 milliseconds, give or
take. You might recall that movies have 24 frames per second (i.e. 40 ms for
each frame). So if we take a still picture, and move it 24 times per second, it
starts to look animated to us.
</p>
<p>
The same happens with sound! If there is some movement of air more than around
24 times per second, we start perceiving it as sound. Less than that, we hear
them as individual musical notes.
</p>
<p>
So the number of beeps have to be less than 24 for us to hear them as individual
beeps and not as a single sound. In practice, this threshold varies depending on
the exact sound being played and a lot of other factors. 7 per second is a
conservative value that we'll always hear as events and not as a single sound.
</p>
<p>
7 is also interesting for other reasons (e.g.
<a href="/raag/bhairav">musical scales usually max out at 7 notes</a>, even
though there are 12 available to us). This might be related to <i>The Magical
Number Seven, Plus or Minus Two</i>, but this aside is already too long and I'm
now ranting.
</p>
</small>
</blockquote>
<h3>Rest of the owl</h3>
<p>
Those of you in the know might've winced at my using <code>setInterval</code> above to set
the time between individual notes.
</p>
<p>
Even though we can't hear individual notes smaller than say 40 milliseconds, we
are still surprisingly sensitive to other aspects of sound at smaller
timescales. We can perceive music as being "out of beat" even if notes are off
by, say, 10 ms. For some aspects like the attack time, we're sensitive to
millisecond level differences.
</p>
<p>
The <code>setInterval</code> function in JavaScript has too much jitter for it
to be useful for triggering musical events.
</p>
<p>
Fortunately, there is an alternative. The time kept by WebAudio itself is
precise (we used it above as <code>ctx.currentTime</code>). We can tell WebAudio
to do something at a particular time, and it'll do it exactly then.
</p>
<p>
Unfortunately, Safari spoils the party here. Safari throttles both
<code>setInterval</code> (and its better alternative,
<code>requestAnimationFrame</code>) when the user switches tabs. While WebAudio
time is precise, we still need to <em>generate</em> and schedule the next batch
of events if we're trying to play a generative piece of music, where it is
expected that the user will keep our tab running in the background instead of
staring at it.
</p>
<p>
So WebAudio's standard APIs are not helpful for playing long generative pieces
of music. For that, we'll need to use the more advanced option of AudioWorklets
instead which run unthrottled in the background.
</p>
<p>
That's for a future post. But keep in mind that if you're not looking for
background music, the standard APIs might be enough. <a
href="https://github.com/mnvr/mrmr.io/blob/main/raag/synth.ts">Here is a small
synth</a> with a lot of source code comments explaining the aspects we covered
here in more depth.
</p>
<p>
I also wrote a tutorial on
<a href="/euclidean-rhythms">making music using Euclidean rhythms</a>.
</p>
</body>
</html>