-
Notifications
You must be signed in to change notification settings - Fork 2
/
metronome.html
384 lines (347 loc) · 9.77 KB
/
metronome.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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
<!DOCTYPE html>
<html>
<head>
<title>Metronome</title>
<link rel="icon" href="res/favicon.ico">
<script type="text/javascript">
function lerp(t, x0, x1) {
return t * (x1 - x0) + x0;
}
function unlerp(x, x0, x1) {
return (x - x0) / (x1 - x0);
}
function wrap(x) {
return ((x % 1) + 1) % 1;
}
function cubicEaseOut(x) {
return (3 - x * x) * x / 2;
}
async function asyncXMLHttpRequest(url, type) {
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = type;
request.onload = () => resolve(request.response);
request.onerror = reject;
request.send();
});
}
class LiveValue {
constructor(id, format) {
this.value = null;
this._input = document.getElementById(id);
this._view = document.getElementById(`${id}_view`);
this._format = format;
this.update();
}
update() {
this.value = parseFloat(this._input.value);
this._view.innerText = this._format(this.value);
return this.value;
}
}
class Tick {
constructor(ctx, sound, t, volume, detune) {
this.gainNode = ctx.createGain();
this.gainNode.gain.value = volume;
this.tickNode = ctx.createBufferSource();
this.tickNode.detune.value = detune;
this.tickNode.buffer = sound;
this.tickNode.connect(this.gainNode);
this.gainNode.connect(ctx.destination);
this.tickNode.start(t);
this.ctx = ctx;
}
onEnd(fn) {
this.tickNode.addEventListener('ended', fn);
}
stop() {
this.gainNode.gain.linearRampToValueAtTime(0, this.ctx.currentTime + 0.01);
}
}
class Metronome {
constructor() {
this.spb = null;
this.swing = null;
this.playing = false;
this.lastBeatTime = 0;
this.nextBeatTime = 0;
this.tickSound = null;
this.currentDownTick = null;
this.currentUpTick = null;
this.delayedSuspend = 0;
this.epoch = 0;
this.ctx = new AudioContext();
this.ctx.suspend();
window.setTimeout(async () => {
const response = await asyncXMLHttpRequest(
'https://tiusic.com/res/tick.wav', 'arraybuffer');
this.tickSound = await this.ctx.decodeAudioData(response);
}, 0);
}
play() {
window.clearTimeout(this.delayedSuspend);
this.ctx.resume();
this.playing = true;
this.nextBeatTime = this.ctx.currentTime + 0.1;
this.lastBeatTime = this.nextBeatTime - (60 / this.bpm);
this._update(this.epoch);
}
stop() {
this.playing = false;
this.epoch += 1;
this.currentDownTick?.stop();
this.currentUpTick?.stop();
this.currentDownTick = this.currentUpTick = null;
this.delayedSuspend = window.setTimeout(() => {
this.ctx.suspend();
this.delayedSuspend = 0;
}, 1000);
}
config(bpm, swing) {
this.bpm = bpm;
this.swing = swing;
}
isPlaying() {
return this.playing;
}
_update(epoch) {
if (epoch != this.epoch || !this.isPlaying()) return;
// Schedule the next 2 tick sounds (the down beat and up beat). We attach
// the scheduling of the subsequent beat to when the down beat sound
// finishes playing. This lets us play even when the tab is in the
// background (ie when window.setTimeout etc stop working).
//
// This relies on the fact that the tick sound is about 0.05 seconds long,
// and the fastest BPM we support is 300, which is a gap between beats of
// 0.2 seconds. If the tick sound was longer than this gap, the sounds could
// overlap and this approach wouldn't work.
// Calculate when the following beat will be.
this.lastBeatTime = this.nextBeatTime;
this.nextBeatTime = this.lastBeatTime + (60 / this.bpm);
// Downbeat.
this.currentDownTick = this._tick(this.lastBeatTime, 1.0, 1000);
this.currentDownTick.onEnd(() => this._update(epoch));
// Upbeat.
const frac = lerp(this.swing / 100, 1 / 2, 2 / 3);
const uptime = lerp(frac, this.lastBeatTime, this.nextBeatTime);
this.currentUpTick = this._tick(uptime, 0.1, 500);
}
_tick(t, volume, detune) {
return new Tick(this.ctx, this.tickSound, t, volume, detune);
}
beatFrac() {
return wrap(unlerp(
this.ctx.currentTime, this.lastBeatTime, this.nextBeatTime));
}
}
function geometricDelta(x, y) {
// 0: same, 1: very different.
return 1 - (x < y ? x / y : y / x);
}
class BpmDetector {
constructor() {
this.bpm = -2; // -2: never tapped, -1: tapped once, >0: active
this.lastTap = 0;
}
tap() {
const t = performance.now() * 1e-3;
if (this.bpm == -2) {
// Never tapped. Update the time and move to the next BPM state.
this.bpm = -1;
} else {
const newBpm = 60.0 / (t - this.lastTap);
if (this.bpm == -1 || geometricDelta(this.bpm, newBpm) > 0.2) {
// This is the first BPM calculation or the BPM has changed drastically,
// so just set the BPM to the new value, rather than smoothly updating.
this.bpm = newBpm;
} else {
// Smoothly update the BPM.
this.bpm += 0.1 * (newBpm - this.bpm);
}
}
this.lastTap = t;
return this.bpm;
}
}
const kPlayButton = "M1 12C1 5.92487 5.92487 1 12 1C18.0751 1 23 5.92487 23 12C23 18.0751 18.0751 23 12 23C5.92487 23 1 18.0751 1 12ZM9.64109 7.19733C9.14132 6.89192 8.5 7.2516 8.5 7.83729V16.1627C8.5 16.7484 9.14132 17.1081 9.64109 16.8027L16.4528 12.64C16.9313 12.3475 16.9313 11.6525 16.4528 11.36L9.64109 7.19733Z";
const kPauseButton = "M1 12C1 5.92487 5.92487 1 12 1C18.0751 1 23 5.92487 23 12C23 18.0751 18.0751 23 12 23C5.92487 23 1 18.0751 1 12ZM8 8C8 7.44772 8.44772 7 9 7H10C10.5523 7 11 7.44772 11 8V16C11 16.5523 10.5523 17 10 17H9C8.44772 17 8 16.5523 8 16V8ZM13 8C13 7.44772 13.4477 7 14 7H15C15.5523 7 16 7.44772 16 8V16C16 16.5523 15.5523 17 15 17H14C13.4477 17 13 16.5523 13 16V8Z";
function emptyDiv(n) {
while (n.hasChildNodes()) n.removeChild(n.lastChild);
}
function makeElementNS(ns, tag, parent, attr) {
const node = document.createElementNS(ns, tag);
if (parent != null) parent.appendChild(node);
for (const [k, v] of attr) node.setAttribute(k, v);
return node;
}
function makeButtonSvg(path) {
const ns = 'http://www.w3.org/2000/svg';
const svg = makeElementNS(ns, 'svg', null, [['viewBox', '0 0 24 24']]);
makeElementNS(ns, 'path', svg, [
['fill-rule', 'evenodd'], ['clip-rule', 'evenodd'],
['fill', 'var(--svgcolor)'], ['d', path],
]);
return svg;
}
function onLoad() {
const bpm = new LiveValue('bpm', x => `${x}`);
const swing = new LiveValue('swing', x => `${x}%`);
const svgPlay = makeButtonSvg(kPlayButton);
const svgPause = makeButtonSvg(kPauseButton);
const setupToggle = (id, onChange) => {
const button = document.getElementById(id);
let value = true;
const update = () => {
value = !value;
onChange(button, value);
};
button.addEventListener('click', update);
update();
};
const metronome = new Metronome();
setupToggle('play_button', (playButton, value) => {
emptyDiv(playButton);
if (value) {
playButton.appendChild(svgPause);
metronome.play();
} else {
playButton.appendChild(svgPlay);
metronome.stop();
}
});
const bgColor = (playing, x) => {
if (!playing) return '#212121';
const g = Math.floor(lerp(cubicEaseOut(x), 0x42, 0x21));
return `rgb(${g}, ${g}, ${g})`;
};
const frame = () => {
metronome.config(bpm.update(), swing.update());
const clr = bgColor(metronome.isPlaying(), metronome.beatFrac());
document.body.style.setProperty('background-color', clr);
window.requestAnimationFrame(frame);
};
frame();
const bpmDetector = new BpmDetector();
const domBpmOutput = document.getElementById('bpm_output');
document.getElementById('tap_button').addEventListener('click', () => {
const bpm = bpmDetector.tap();
domBpmOutput.innerText = bpm < 0 ? '' : `${bpm.toFixed(1)} BPM`;
});
}
window.addEventListener('load', onLoad);
</script>
<style>
body {
background-color: #212121;
margin: 0;
}
#head {
background-color: #424242;
width: 100%;
display: flex;
justify-content: space-around;
margin-bottom: 16px;
}
h1, #index {
color: #ffc107;
text-align: center;
font-family: monospace;
font-size: 42px;
flex-grow: 1;
padding: 16px;
margin: 0;
}
#index {
color: #ff5722;
text-decoration: none;
flex-grow: 0;
}
#wrap {
padding: 0 16px;
color: #f5f5f5;
font-family: monospace;
font-size: 32px;
display: flex;
flex-direction: column;
align-items: center;
}
.row {
display: flex;
flex-direction: row;
}
.view {
width: 96px;
}
.label {
width: 128px;
}
input {
width: 196px;
}
#play_button {
display: block;
width: 128px;
height: 128px;
font-weight: bold;
cursor: pointer;
}
#play_button svg path {
--svgcolor: #ffc107;
}
#play_button:hover svg path {
--svgcolor: #f5f5f5;
}
.hr {
width: 100%;
border: 1px solid #424242;
margin: 32px 0;
}
#tap_button {
margin-left: 16px;
background-color: #ffc107;
border-radius: 8px;
padding: 0 16px;
color: #212121;
font-weight: bold;
cursor: pointer;
user-select: none;
}
#tap_button:hover {
background-color: #f5f5f5;
}
#bpm_output {
color: #1e88e5;
}
</style>
</head>
<body>
<div id="head">
<a id="index" href="index.html"><</a>
<h1>Metronome</h1>
</div>
<div id="wrap">
<div class="row">
<span class="label">BPM:</span>
<span class="view" id="bpm_view"></span>
<input type="range" id="bpm" min="30" max="300" step="1" value="60"/>
</div>
<div class="row">
<span class="label">Swing:</span>
<span class="view" id="swing_view"></span>
<input type="range" id="swing" min="0" max="150" step="5" value="0"/>
</div>
<div class="row">
<span id="play_button"></span>
</div>
<div class="hr"></div>
<div class="row">
<span>Detect BPM:</span>
<span id="tap_button">TAP</span>
</div>
<div class="row">
<span id="bpm_output"></span>
</div>
</div>
</body>
</html>