-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
73 lines (60 loc) · 1.53 KB
/
index.js
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
module.exports = function (ac, opts) {
var bpm
, oneMinute = 60
, playback = false
, beatLength
, lastBeat
, offset
, swingPercent
, rush = false
, lookahead
ee = opts.ee || require('nee')()
opts = opts || {}
bpm = opts.bpm || 120
swingPercent = opts.swing || 1 // int from 0 - 1
lookahead = opts.lookahead || 0.100
ee.on('schedule-play', play)
ee.on('schedule-stop', stop)
ee.on('bpm-change', changeBpm)
ee.on('swing-change', changeSwing)
return (
{ play: play
, stop: stop
, changeBpm: changeBpm
, changeSwing: changeSwing
, on: ee.on
}
)
function play () {
offset = ac.currentTime
lastBeat = ac.currentTime - offset
playback = true
clock()
}
function stop () {
playback = false
}
function changeBpm (_bpm) { bpm = _bpm }
function changeSwing (_swingPercent) { swingPercent = _swingPercent }
function clock () {
beatLength = oneMinute / bpm
var now = ac.currentTime - offset
, swingLength = swingPercent * (beatLength / 3)
, currentSwing = rush ? swingLength : -swingLength
, swingBeatLength = beatLength + currentSwing
if (lastBeat + swingBeatLength < now) {
lastBeat += swingBeatLength
rush = !rush
}
var beatEvt = (
{ now: now
, beatLength: beatLength
, lookahead: now + lookahead
, lastBeat: lastBeat
, nextBeat: lastBeat + swingBeatLength
}
)
ee.emit('next-tick', [beatEvt])
if (playback) window.requestAnimationFrame(clock)
}
}