summaryrefslogtreecommitdiff
path: root/public/js/grid.js
blob: cc7c3a69ed29a665b98a0e52b596314778c7094e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
var bufferSize = 4096; // 65536 / 2;
var sampleRate = 44100;
var latency = 1000 * bufferSize / sampleRate;
var audioletReady = false;

var samples = [
  'KickDrum0001.wav',
  'Clap.wav',
  'Closed Hihat0001.wav',
  'Open Hihat0001.wav',
  'SnareDrum0001.wav',
  'Clav.wav',
  'Mid Tom0001.wav',
  'Rimshot.wav',
];

function Sampler (audiolet, url) {
  var base = this;
  this.audiolet = audiolet;
  
  // first get the sample and load it into a buffer
  this.buffer = new AudioletBuffer(1, 0);
  this.buffer.load(url, true, function(){

    // connect the buffer to a player and set up the objects we need

    // TriggerControl: [initial trigger state = 0]
    base.trigger = new TriggerControl(base.audiolet, 0);
    
    // BufferPlayer: [buffer] [playbackRate = 1] [startPosition = 0] [loop = 0] [onComplete]
    base.player = new BufferPlayer(base.audiolet, base.buffer, 1, 0, 0);
    base.player.playing = false;

    base.gain = new Gain(base.audiolet, 0.5);
  
    // trigger -> player -> gain -> OUTPUT
    base.gain.connect(base.audiolet.output, 0);
    base.player.connect(base.gain, 0);
    base.trigger.connect(base.player, 0, 1);

  });
  
  this.mute = function(){
    base.gain.setValue(0);
  }
  this.unmute = function(){
    base.gain.setValue(0.5);
  }
}

function Sequencer (audiolet, instrument) {
  var base = this;
  this.audiolet = audiolet;
  this.instrument = instrument;
  this.pattern = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0];

  // building a sequencer ...
  // this makes each note a sixteenth note, and sets up an empty bar
  var durations = new PSequence([0.30, 0.20], Infinity);
  var sequence = new PSequence(this.pattern, Infinity);
  
  this.audiolet.scheduler.play([sequence], durations, function (note, duration) {
    if (note == 1) {
      base.instrument.player.playing = true;
      base.instrument.trigger.trigger.setValue(1);
    }
  });
}

function AudioletApp () {
  this.audiolet = new Audiolet(sampleRate, 2, bufferSize);
  this.audiolet.scheduler.setTempo(90);
  this.sequencers = [];
  
  for (var i in samples) {
    var sample = "/wav/" + samples[i];
    var sampler = new Sampler(this.audiolet, sample);
    var sequencer = new Sequencer(this.audiolet, sampler);
    sequencer.sample = sample;
    this.sequencers.push(sequencer);
  }
}

var Audio = new AudioletApp();

function Grid (app){
  var base = this;

  function setNote (data) {
    Audio.sequencers[data.channel].pattern[data.step] = data.state;
    drawNote(data.step, data.channel);
  };
  
  base.setBeat = function(beatId) {
    beat = beatId;
  };
  
  base.toggle = toggle;

  var playing = false;
  var playingInterval = false;
  var tick;
  var tempo = 125;
  setTempo(tempo);
  var activecoloron = 'rgb(255,255,255)';
  var activecoloroff = 'rgb(202,202,202)';
  var inactivecoloron = 'rgb(52,52,54)';
  var inactivecoloroff = 'rgb(28,28,38)';
  var gridSize = Math.floor(600/16);
  var lastStep = 16;
  var channelCount = 8;
  var beat = lastStep-1;
  var inset = 5;

	var canvas = document.getElementById('canvas'); //.offset();
	var ctx = canvas.getContext('2d');
  init();
  
  function init(){
    bind();
    makeGrid();
  }

  // Bind events
  function bind(){
    
    // Server events
    app.receive("event-grid", loadGrid);
    app.receive("event-note", setNote);
    
    // UI events
  	$('#start').click(start);
  	$('#stop').click(stop);
  	$('#tempo').change(function() {
  	  setTempo( $('#tempo').val() )
  	});
  	
  	// Clicking the canvas
  	$('#canvas').click(canvasClick);
  }

  // Click a square on the canvas to toggle it.
	function canvasClick (e){
    var x = e.pageX-canvas.offsetLeft-10;
    var y = e.pageY-canvas.offsetTop-10;

  	var step    = Math.floor(x / gridSize);
  	var channel = Math.floor(y / gridSize);

  	toggleNote(channel, step);
  	
  	// Let the other clients know the new state
  	app.send("event-note", {
  	  'step': step,
  	  'channel': channel,
  	  'state': Audio.sequencers[channel].pattern[step]
  	});
  }
  
  // Load the pattern from the server
  function loadGrid(data){

    for (var channel = 0; channel < channelCount; channel++) {
      for (var step = 0; step < lastStep; step++) {
        Audio.sequencers[channel].pattern[step] = data.pattern[channel][step];
      }
    }
    
    tempo = data.tempo;
    stop();
    start();
  }
  
  // Toggle on/off
  function toggle(){
    playing ? stop() : start();
  }

  // Start playing
  function start() {
  	reset();
  	playing = true;
  	makeGrid();
  	document.body.bgColor = "#000000";
    playingInterval = setInterval(make, tick);
  }
  
  // Stop playing
  function stop() {
  	reset();
  	playing = false;
  	document.body.bgColor = "#444444";
  }
  
  // Clear the canvas, reset everything to zero, stop the event loop
  function reset() {
  	clearInterval(playingInterval);
  	ctx.clearRect(0,0, canvas.width, canvas.height);
  	beat = lastStep-1;
  }
  
  // Change the tempo
  function setTempo(tempo) {
    tempo = parseInt(tempo);
  	if (tempo <= 30 || tempo >= 300)	{
  		tempo = 120;
  	}
  	Audio.audiolet.scheduler.setTempo(tempo);
  	tick = (1000 / (tempo / 60)) / 4;
  	$("#alertDisp").html( "Set tempo to " + tempo );
  	if (playing) {
  		clearInterval(playingInterval);
  		playingInterval = setInterval(make, tick);
  	}
  }

  // Paint the current step that's playing, and reset the previous stamp
  // This is the old event loop
  function make() {
  	beat += 1;
  	if (beat == lastStep)	{
  		makeColumn(beat-1, activecoloroff, inactivecoloroff, false);
  		makeColumn(0,      activecoloron,  inactivecoloron,  true);
  		beat = 0;
  	}
  	else {
  		makeColumn(beat,   activecoloron,  inactivecoloron,  true);
  		makeColumn(beat-1, activecoloroff, inactivecoloroff, false);
  	}
  }
  
  // Paint the rectangles in a column, if any of them are playing.
  function makeColumn(step, active, inactive, playing) {
  	for (var channel = 0; channel < channelCount; channel += 1) {
  		if (Audio.sequencers[channel].pattern[step] == 1)	{
  			if (playing === true)	{
  				ctx.fillStyle = random_color();
  			}
  			else	{
  				ctx.fillStyle = active;
  			}
  			ctx.fillRect( (step*gridSize) + inset, (channel*gridSize) + inset,
                			gridSize - 2*inset,      gridSize - 2*inset );
  		}
  	}
  }

  // Paint all the squares on the grid
  function makeGrid() {
  	for (var step = 0; step < lastStep; step += 1)	{
  		for (var channel = 0; channel < channelCount; channel += 1)	{
  			if (Audio.sequencers[channel].pattern[step] == 1)	{
  				ctx.fillStyle = activecoloroff;
  			}
  			else {
      		ctx.fillStyle = step % 4 ? inactivecoloroff : inactivecoloron;
  			}
  			ctx.fillRect((step*gridSize) + inset, (channel*gridSize) + inset, gridSize - 2*inset, gridSize - 2*inset);
  		}
  	}
  }
  
  // Repaint a square to toggle it
  function drawNote(channel, step) {
  	if (Audio.sequencers[channel].pattern[step] == 1) {
  		ctx.fillStyle = activecoloroff;
    } else {
  		ctx.fillStyle = step % 4 ? inactivecoloroff : inactivecoloron;
    }
		ctx.fillRect((step*gridSize) + inset, (channel*gridSize) + inset, gridSize - 2*inset, gridSize - 2*inset);
  }
  
  // Actually toggle a note, and then redraw it
  function toggleNote(channel, step) {
  	if (Audio.sequencers[channel].pattern[step] == 1) {
  		Audio.sequencers[channel].pattern[step] = 0;
  	}
    else {
  		Audio.sequencers[channel].pattern[step] = 1;
  	}
  	drawNote(channel, step);
  }

  // Generate a random color
  function random_color() {
  	var rint = Math.round(0xffffff * Math.random());
  	return 'rgb(' + (rint >> 16) + ',' + (rint >> 8 & 255) + ',' + (rint & 255) + ')';
  }

};