Last active
July 5, 2016 12:32
-
-
Save mohayonao/c3fb6d850be80ef8642afa9453365076 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| "use strict"; | |
| const events = require("events"); | |
| class BeatEmitter extends events.EventEmitter { | |
| constructor(transport, api) { | |
| super(); | |
| this.transport = transport; | |
| this.api = api || global; | |
| this._running = false; | |
| this._ticks = -1; | |
| this._loop = this._loop.bind(this); | |
| } | |
| start() { | |
| if (!this._running) { | |
| this._running = true; | |
| this.api.setImmediate(this._loop); | |
| } | |
| return this; | |
| } | |
| stop() { | |
| this._running = false; | |
| return this; | |
| } | |
| _loop() { | |
| const beat = this.transport(this.api.Date.now() / 1000); | |
| if (beat.ticks !== this._ticks) { | |
| this._ticks = beat.ticks; | |
| this.emit("beat", beat); | |
| } | |
| if (this._running) { | |
| this.api.setImmediate(this._loop); | |
| } | |
| } | |
| } | |
| module.exports = BeatEmitter; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| "use strict"; | |
| function bpmsec(bpm, len) { | |
| len = len || 4; | |
| return (60 / bpm) * (4 / len); | |
| } | |
| function makeTransport(bpm, len) { | |
| len = len || 4; | |
| const unitTicks = bpmsec(bpm, len); | |
| const beatsLen = len / 4; | |
| return (time) => { | |
| const ticks = Math.floor(time / unitTicks); | |
| const bars = Math.floor(ticks / len); | |
| const beats = Math.floor(ticks / beatsLen) % 4; | |
| const units = ticks % len; | |
| return { bars, beats, units, ticks }; | |
| }; | |
| } | |
| module.exports = makeTransport; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| "use strict"; | |
| const makeTransport = require("./makeTransport"); | |
| const BeatEmitter = require("./BeatEmitter"); | |
| const transport = makeTransport(120, 32); | |
| const beat = new BeatEmitter(transport); | |
| beat.on("beat", (beat) => { | |
| console.log(beat); | |
| }); | |
| beat.start(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment