Skip to content

Instantly share code, notes, and snippets.

@pce
Created October 31, 2012 19:48
Show Gist options
  • Save pce/3989361 to your computer and use it in GitHub Desktop.
Save pce/3989361 to your computer and use it in GitHub Desktop.
StepSequencer without GUI with gamejs
var gamejs = require('gamejs');
var mixer = require('gamejs/mixer');
var stepsequencer = require('stepsequencer');
var FPS = 60;
var BPM = 100;
var extAudio = ".ogg";
// var extAudio = ".wav";
function main() {
var display = gamejs.display.setMode([500, 350]);
var font = new gamejs.font.Font('20px monospace');
var sndKick = new gamejs.mixer.Sound('data/kick1'+extAudio);
var sndSnare = new gamejs.mixer.Sound('data/snare1'+extAudio);
var sndHiHat = new gamejs.mixer.Sound('data/hihat1'+extAudio);
var sndHiHat2 = new gamejs.mixer.Sound('data/hihat2'+extAudio);
var seq = new stepsequencer.StepSequencer();
seq.addAction(0, 0, sndKick);
seq.addAction(0, 3, sndKick);
seq.addAction(0, 9, sndKick);
seq.addAction(1, 4, sndSnare);
seq.addAction(1, 12, sndSnare);
for (var i=0; i < 16; i++) {
if (i%4==0) continue;
seq.addAction(2, i, sndHiHat);
}
for (var i=0; i < 16; i+=4) {
seq.addAction(2, i, sndHiHat2);
}
function seqUpdate () {
seq.update();
};
/**
* tick
*/
function tick () {
// event handling
gamejs.event.get().forEach(function(event) {
if (event.type === gamejs.event.KEY_DOWN) {
} else if (event.type === gamejs.event.MOUSE_MOTION) {
}
});
// draw
display.clear();
display.blit(font.render(seq._step, '#ff0000'), [250, 50]);
};
gamejs.time.fpsCallback(tick, this, FPS);
// FPS*60 = FPM, FPM/BPM
// TODO bind to High Resolution Timer
gamejs.time.fpsCallback(seqUpdate, this, 6 );
};
gamejs.preload([
'data/kick1.wav',
'data/kick1.ogg',
'data/kick1.wav',
'data/snare1.ogg',
'data/snare1.wav',
'data/hihat1.ogg',
'data/hihat1.wav',
'data/hihat2.ogg',
'data/hihat2.wav'
]);
gamejs.ready(main);
var StepSequencer = exports.StepSequencer = function(bpm, fps) {
this._bpm = bpm || 120;
this._fps = fps || 60;
this._tick = 0;
this._step = 0;
this._actions = {};
this._stepCount = 16;
this._layers = 0;
this.addAction = function(layer, index, item) {
if (typeof this._actions[layer] == 'undefined') {
this._actions[layer] = {};
this._layers++;
}
this._actions[layer][index] = item;
};
this.update = function() {
for (var layer=0; layer < this._layers + 1; layer++) {
if (typeof this._actions[layer] != 'undefined'
&& typeof this._actions[layer][this._step] != 'undefined') {
this._actions[layer][this._step].play();
}
}
this._step++;
if ((this._step % this._stepCount)==0) {
this._step = 0;
}
};
this.tick = function() {
// tick is a FPS helper
if (((this._tick / this._fps) * this._bpm) % this._stepCount ==0 ) {
this.update();
}
this._tick++;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment