xxxxxxxxxx
117
// Sequencer
var nSteps = 8;
var nTracks = 8;
var cells = [];
var currentStep = 0;
var beats = 0;
var cellWidth, cellHeight;
// Sound
var noteNames = ["A1", "B1", "C2", "D2", "E2", "F2", "G2", "A2"];
var player = new Tone.Sampler(
{
"A1" : "samples/casio/A1.mp3",
"C2" : "samples/casio/C2.mp3",
"E2" : "samples/casio/E2.mp3",
"G2" : "samples/casio/G2.mp3"
}
);
player.toMaster();
Tone.Transport.scheduleRepeat(onBeat, "16n");
Tone.Transport.bpm.value = 40;
// Visuals
var t = 30;
var l = 25;
var gridWidth, gridHeight, cellWidth, cellHeight;
var blue;
var colors = ["#df365d", "#f2924d", "#ebd64e", "#97c348", "#4ab4a1", "#4f64d5", "#bd51a6"];
function setup() {
// Visuals
createCanvas(600, 300);
gridWidth = width - 2*l;
gridHeight = height - 2*t;
cellWidth = gridWidth / nSteps;
cellHeight = gridHeight / nTracks;
blue = color(178, 223, 247);
// Sound
Tone.Transport.start();
// Sequencer
// Initialize all sequencer cells.ON: 1. OFF: 0.
for(var track = 0; track < nTracks; track++){
cells[track] = [];
for(var step = 0; step < nSteps; step++){
cells[track][step] = 0;
}
}
}
function onBeat(time){
// If the current beat is on, play it
for(var track = 0; track < nTracks; track++){
if(cells[track][currentStep] == 1){
var note = noteNames[(noteNames.length - track - 1) % noteNames.length];
player.triggerAttack(note, time);
}
}
beats++;
currentStep = beats % nSteps;
}
function draw(){
background(255);
// Draw cells that are on
for(var step = 0; step < nSteps; step++){
for(var track = 0; track < nTracks; track++){
if(cells[track][step] == 1){
var notePos = nTracks - 1 - track;
var col = colors[notePos % 7];
fill(col);
rect(l+ step*cellWidth, t + track*cellHeight, cellWidth, cellHeight);
}
}
}
stroke(blue);
// Draw horizontal lines
for(var i = 0; i <= nTracks; i++){
var y = t + i*cellHeight;
right = width - l;
line(l, y, right, y);
}
// Draw vertical lines
for(var i = 0; i <= nSteps; i++){
var x = i*cellWidth;
line(l + x, t, l + x, t + gridHeight);
}
// Highlight current step
if(beats > 0){
var highlight = (beats - 1) % nSteps;
fill(178, 223, 247, 50);
noStroke();
rect(l + highlight * cellWidth, t, cellWidth, gridHeight)
}
}
function mousePressed(){
// If the mouse is within the bounds of the canvas
if( l < mouseX && mouseX < l + gridWidth &&
t < mouseY && mouseY < t + gridHeight){
// Account for margins
var x = mouseX - l;
var y = mouseY - t;
// Determine which cell the mouse is on
var i = floor(y / cellHeight);
var j = floor(x / cellWidth);
// Toggle cell on/off
cells[i][j] = !cells[i][j];
}
}