MIDI Matrix


javascript generated sound owes credit to MIDI.js

The demo is an imitation of Andre Michelle'sToneMatrix.


var matrix;
var canvas;
var ctx;
var row;
var col;

var notes = [
[0,1,2,3,4,5,6,7,8,9,11,12],
[12,0,1,2,3,4,5,6,7,8,9,11],
[11,12,0,1,2,3,4,5,6,7,8,9],
[9,11,12,0,1,2,3,4,5,6,7,8],
[8,9,11,12,0,1,2,3,4,5,6,7],
[7,8,9,11,12,0,1,2,3,4,5,6],
[6,7,8,9,11,12,0,1,2,3,4,5],
[5,6,7,8,9,11,12,0,1,2,3,4],
[4,5,6,7,8,9,11,12,0,1,2,3],
[3,4,5,6,7,8,9,11,12,0,1,2],
[2,3,4,5,6,7,8,9,11,12,0,1],
[1,2,3,4,5,6,7,8,9,11,12,0]
];

function makeNotes(){
	var base = [1,3,6,8,10,13,15,18,20,22,25,27];
	for(var i = 0; i < 12; i++){
		for(var j = 0; j < 12; j++){
			notes[i][j] = base[(i+j)%12];
		}
	}
}

function drawMatrix(){
	for(col = 0; col < 12; col++){
		for(row = 0; row < 12; row++){
			if(matrix[row][col]){
				ctx.fillStyle = "blue";
			}else{
				ctx.fillStyle = "black";
			}
			ctx.fillRect(col*40+2,row*40+2,36,36);
		}
	}
}

function freshMatrix(){
	var trix = [];
	for(col = 0; col < 12; col++){
		trix.unshift([]);
		for(row = 0; row < 12; row++){
			trix[0].push(0);
		}
	}
	return trix;
}



window.onload = function () {
	
	canvas = document.getElementById("matrix");
	ctx = canvas.getContext("2d");
	
	matrix = freshMatrix();
	
	$("#matrix").click(function(e){
		var clicked = [0,0];
		clicked[0] = Math.floor(e.offsetY/40);
		clicked[1] = Math.floor(e.offsetX/40);
		matrix[clicked[0]][clicked[1]] = (matrix[clicked[0]][clicked[1]] + 1)%2;
		drawMatrix();
	});
	
drawMatrix();
	
	makeNotes();
	
	MIDI.loadPlugin({
		soundfontUrl: "MIDIjs/soundfont/",
		instrument: "acoustic_grand_piano",
		callback: function() {
			var delay = 0; // play one note every quarter second
			var note = 55; // the MIDI note
			var velocity = 127; // how hard the note hits
			// play the note
			MIDI.setVolume(0, 100);
			MIDI.noteOn(0, note, velocity, delay);
			MIDI.noteOff(0, note, delay + 0.75);
			
			setInterval(function(){
				var t = 0;
				for(var i = 0; i < 12; i++){
					setTimeout(function(){
						drawMatrix();
						ctx.fillStyle="rgba(255,255,255,0.2)";
						ctx.fillRect(t*40,0,40,480);
							for(row = 0; row < 12; row++){
								if(matrix[row][t]){
									MIDI.setVolume(0, 127);
									MIDI.noteOn(0, note+notes[row][t], velocity, delay);
									MIDI.noteOff(0, note+notes[row][t], delay + 0.75);
									ctx.fillStyle="green";
									ctx.fillRect(t*40+2,row*40+2,36,36);
								}
							}
							t++;
					}, i*100);
				}
			}, 1400);
		
		}
	});
};


`