Skip to content

Instantly share code, notes, and snippets.

@mohayonao
Last active July 5, 2016 12:32
Show Gist options
  • Select an option

  • Save mohayonao/c3fb6d850be80ef8642afa9453365076 to your computer and use it in GitHub Desktop.

Select an option

Save mohayonao/c3fb6d850be80ef8642afa9453365076 to your computer and use it in GitHub Desktop.
"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;
"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;
"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