-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMetronome.ts
406 lines (349 loc) · 8.61 KB
/
Metronome.ts
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
import { getAudioContext } from '../audio-context'
import { PreciseTimer } from './PreciseTimer'
import { EventEmitter } from '../event'
import { Score, createScore } from '../score'
import { MetronomePosition, MetronomeTimeSignature } from './types'
export * from './types'
/**
* Initial position
* - `beatIndex` = `0` (first beat index)
* - `currentMeasure` = `1`
* - `currentBeat` = `1`
*/
export const initialPosition: MetronomePosition = {
beatIndex: 0,
// metronomeBeat: 1,
currentMeasure: 1,
currentBeat: 1,
}
/**
* Metronome runs a precise timer that can start, pause, and stop.
*
* It has a tempo and time signature, which control how time is counted.
*
* It keeps track of the current position in these units of measurement:
*
* - Absolute beat index
* - By measure and beat, based on time signature which can change
*
* It can be given a score of players with events, which will be played in sync
* with the metronome.
*
* @example
* ```ts
* import { Metronome } from 'mooz/metronome'
* ```
*/
export class Metronome extends EventEmitter {
/**
* Audio context
*/
audioContext: AudioContext
/**
* Tempo in beats per minute
*/
tempo = 60
/**
* Time signature
*/
timeSignature: MetronomeTimeSignature = {
numberOfBeats: 4,
beatUnit: 4,
}
/**
* Metronome position
*/
position: MetronomePosition = {
beatIndex: 0,
// metronomeBeat: 0,
currentMeasure: 1,
currentBeat: 1,
}
/**
* Current score
*/
score: Score
/**
* Precise timer
*/
private timer: PreciseTimer
/**
* Listener callbacks for next measure
*/
private nextMeasureListeners: Function[] = []
/**
* Reset position is scheduled
*/
private resetPositionScheduled: boolean = false
/**
* Loop duration by absolute beat index
*/
loopDuration = 0
constructor(
props: {
audioContext?: AudioContext
tempo?: number
timeSignature?: MetronomeTimeSignature
} = {}
) {
super()
const { audioContext = getAudioContext(), tempo, timeSignature } = props
this.audioContext = audioContext
this.timer = new PreciseTimer({
context: audioContext,
})
if (tempo) {
this.tempo = tempo
}
if (timeSignature) {
this.timeSignature = timeSignature
}
this.setScore(createScore())
}
/**
* Set loop duration by absolute beat index
*/
setLoop(duration: number) {
this.loopDuration = duration
}
/**
* Callback on absolute beat
*/
private onAbsoluteBeat = (event) => {
let beatIndex = event.isFirstEvent
? this.position.beatIndex // Starts on 0
: this.position.beatIndex + 1
const reset =
this.loopDuration && beatIndex === this.loopDuration //+ 1
if (reset) {
beatIndex = 0
this.resetPositionScheduled = true
}
const { playbackTime } = event
/**
* Schedule score events
*/
const parts = this.score.parts
// Calculate beat duration every time because it can change with tempo
const beatDuration = this.getAbsoluteBeatDuration()
for (const part of parts) {
for (const schedule of part.schedules) {
if (!schedule[beatIndex]) continue
for (const event of schedule[beatIndex]) {
const diff = event.beat - beatIndex
part.player.play({
playbackTime:
diff > 0 ? playbackTime + diff * beatDuration : playbackTime,
...event,
})
}
}
}
const position = {
beatIndex,
playbackTime,
}
/**
* Emit event to schedule the beat
*
* Audio players can use this to schedule sounds precisely.
*/
this.emit('scheduleAbsoluteBeat', position)
this.timer.nextTick(playbackTime, () => {
this.position.beatIndex = beatIndex
/**
* ? Can have race condition if metronome beat comes before absolute,
* or is later..?
*/
if (reset) {
Object.assign({
// metronomeBeat: 1,
currentMeasure: 1,
currentBeat: 1,
})
}
/**
* Emit event for beat
*
* Visual players can use this and requestAnimationFrame to draw
*/
this.emit('absoluteBeat', position)
})
}
/**
* Callback on metronome beat
*/
private onMetronomeBeat = (event) => {
let reset = this.resetPositionScheduled
// let metronomeBeat = this.position.metronomeBeat + 1
let currentMeasure =
reset || event.isFirstEvent ? 1 : this.position.currentMeasure
let currentBeat =
reset || event.isFirstEvent ? 1 : this.position.currentBeat + 1
if (currentBeat > this.timeSignature.numberOfBeats) {
currentMeasure++
currentBeat -= this.timeSignature.numberOfBeats
}
// Reset metronome position
if (reset) {
this.resetPositionScheduled = false
// metronomeBeat = 1
currentMeasure = 1
currentBeat = 1
}
const scheduleProps = {
playbackTime: event.playbackTime,
// metronomeBeat,
currentMeasure,
currentBeat,
}
// Next measure
if (
this.position.currentMeasure !== currentMeasure ||
(this.position.currentMeasure === 1 && this.position.currentBeat === 1)
) {
for (const listener of this.nextMeasureListeners) {
listener(scheduleProps)
}
this.nextMeasureListeners = []
}
this.emit('scheduleMetronomeBeat', scheduleProps)
this.timer.nextTick(event.playbackTime, () => {
// this.position.metronomeBeat = metronomeBeat
this.position.currentMeasure = currentMeasure
this.position.currentBeat = currentBeat
this.emit('metronomeBeat', this.position)
})
}
/**
* Get the duration of an absolute beat in seconds
*/
getAbsoluteBeatDuration = () => {
return (60 / this.tempo) * (4 / 4)
}
/**
* Get the duration of a metronome beat in seconds
*/
getMetronomeBeatDuration = () => {
return (60 / this.tempo) * (4 / this.timeSignature.beatUnit)
}
/**
* Start timer loops
*
* There are two loops to count absolute and metronome beats separately.
*/
private startLoops = (firstEvent) => {
const loops = [
{
callback: this.onAbsoluteBeat,
getInterval: this.getAbsoluteBeatDuration,
},
{
callback: this.onMetronomeBeat,
getInterval: this.getMetronomeBeatDuration,
},
]
loops.forEach(({ getInterval, callback }) => {
const loop = (event) => {
// Schedule current beat
const t0 = event.playbackTime
this.timer.insert(t0, (newEvent) =>
callback(Object.assign(event, newEvent))
)
// Schedule next beat
// Get interval every time for dynamic tempo and time signature
const t1 = t0 + getInterval()
this.timer.insert(t1, loop)
}
loop({
...firstEvent,
isFirstEvent: true,
})
})
}
/**
* Start or resume the timer
*/
start() {
if (this.timer.isPaused) {
this.timer.start() // Resume
} else {
if (!this.timer.isStopped) return // Already started
this.timer.start(this.startLoops)
}
this.emit('start', this.position)
}
/**
* Stop the timer
*/
stop() {
this.timer.stop()
this.nextMeasureListeners = []
this.resetPositionScheduled = false
this.resetPosition()
// this.position.metronomeBeat = 0 // 0 = Stopped, 1 = First beat
this.emit('stop', this.position)
}
/**
* Pause the timer
*/
pause() {
this.timer.pause()
this.emit('pause', this.position)
}
/**
* Destroy instane: stop, remove timer and listeners
*/
destroy() {
this.stop()
this.removeListeners()
this.timer = null
}
/**
* Reset position
*/
resetPosition() {
Object.assign(this.position, initialPosition)
}
/**
* Schedule a callback at given time
*/
schedule(time: number, callback: Function, data?: any) {
this.timer.nextTick(time, () =>
callback({
state: this,
data,
})
)
}
/**
* Schedule a callback for start of next measure
*/
scheduleNextMeasure(callback) {
this.nextMeasureListeners.push(callback)
}
/**
* Set current score
*/
setScore(newScore: Score) {
this.score = newScore
if (this.score.loopDuration) {
this.setLoop(this.score.loopDuration)
}
}
/**
* Set tempo in beats per second
* - Range: 1~999
*/
setTempo(tempo: number) {
if (tempo >= 1 && tempo <= 999) {
this.tempo = tempo
}
}
/**
* Set time signature
*/
setTimeSignature(timeSignature: MetronomeTimeSignature) {
this.timeSignature = timeSignature
}
}