-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscripts.js
478 lines (410 loc) · 18.3 KB
/
scripts.js
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
// scripts.js
const normalStates = ['off', 'on', 'roll', 'flare'];
const lightStates = ['light', 'light-roll', 'light-flare'];
const allStates = ['off', 'on', 'roll', 'flare', 'light', 'light-roll', 'light-flare'];
const rows = ['row-oh', 'row-ch', 'row-hc', 'row-lt', 'row-sd', 'row-bd', 'row-acc'];
const totalPages = 8;
let currentPage = 0;
let lightMode = false;
let isPlaying = false;
let currentStep = 0;
let intervalId;
let currentBPM = parseFloat(localStorage.getItem('sequencerBPM')) || 60;
const calculateStepTime = (bpm) => {
return (60000 / bpm) / 4; // Convert BPM to milliseconds per step
};
document.addEventListener('DOMContentLoaded', () => {
let audioContext;
// Initialize audio context on user interaction
const initAudio = () => {
if (!audioContext) {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
// iOS/Chrome specific unlock
if (audioContext.state === 'suspended') {
const unlock = async () => {
await audioContext.resume();
document.body.removeEventListener('touchstart', unlock);
document.body.removeEventListener('mousedown', unlock);
};
document.body.addEventListener('touchstart', unlock, false);
document.body.addEventListener('mousedown', unlock, false);
}
}
};
const NORMAL_VOLUME = 1.0;
const LIGHT_VOLUME = 0.5;
// Function to create a kick drum sound using a sinewave and an envelope
const playKickSound = (volume = NORMAL_VOLUME) => {
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();
oscillator.type = 'sine';
oscillator.frequency.setValueAtTime(150, audioContext.currentTime); // Start frequency
oscillator.frequency.exponentialRampToValueAtTime(0.001, audioContext.currentTime + 0.5); // End frequency
gainNode.gain.setValueAtTime(volume, audioContext.currentTime); // Start gain
gainNode.gain.exponentialRampToValueAtTime(0.001, audioContext.currentTime + 0.5); // End gain
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
oscillator.start(audioContext.currentTime);
oscillator.stop(audioContext.currentTime + 0.5);
};
// Function to create a noise buffer
const createNoiseBuffer = () => {
const bufferSize = audioContext.sampleRate * 1; // 1 second buffer
const buffer = audioContext.createBuffer(1, bufferSize, audioContext.sampleRate);
const data = buffer.getChannelData(0);
for (let i = 0; i < bufferSize; i++) {
data[i] = Math.random() * 2 - 1; // White noise
}
return buffer;
};
// Function to create an open hi-hat sound
const playOpenHiHatSound = (volume = NORMAL_VOLUME) => {
const bufferSource = audioContext.createBufferSource();
bufferSource.buffer = createNoiseBuffer();
const gainNode = audioContext.createGain();
gainNode.gain.setValueAtTime(volume, audioContext.currentTime); // Start gain
gainNode.gain.exponentialRampToValueAtTime(0.001, audioContext.currentTime + 0.2); // End gain
bufferSource.connect(gainNode);
gainNode.connect(audioContext.destination);
bufferSource.start(audioContext.currentTime);
bufferSource.stop(audioContext.currentTime + 0.2);
};
// Function to create a closed hi-hat sound
const playClosedHiHatSound = (volume = NORMAL_VOLUME) => {
const bufferSource = audioContext.createBufferSource();
bufferSource.buffer = createNoiseBuffer();
const gainNode = audioContext.createGain();
gainNode.gain.setValueAtTime(volume, audioContext.currentTime); // Start gain
gainNode.gain.exponentialRampToValueAtTime(0.001, audioContext.currentTime + 0.1); // End gain
bufferSource.connect(gainNode);
gainNode.connect(audioContext.destination);
bufferSource.start(audioContext.currentTime);
bufferSource.stop(audioContext.currentTime + 0.1);
};
// Function to create a hand clap sound
const playHandClapSound = (volume = NORMAL_VOLUME) => {
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();
oscillator.type = 'square';
oscillator.frequency.setValueAtTime(600, audioContext.currentTime); // Frequency
gainNode.gain.setValueAtTime(volume, audioContext.currentTime); // Start gain
gainNode.gain.exponentialRampToValueAtTime(0.001, audioContext.currentTime + 0.1); // End gain
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
oscillator.start(audioContext.currentTime);
oscillator.stop(audioContext.currentTime + 0.1);
};
// Function to create a low tom sound
const playLowTomSound = (volume = NORMAL_VOLUME) => {
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();
oscillator.type = 'sine';
oscillator.frequency.setValueAtTime(100, audioContext.currentTime); // Start frequency
oscillator.frequency.exponentialRampToValueAtTime(0.001, audioContext.currentTime + 0.5); // End frequency
gainNode.gain.setValueAtTime(volume, audioContext.currentTime); // Start gain
gainNode.gain.exponentialRampToValueAtTime(0.001, audioContext.currentTime + 0.5); // End gain
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
oscillator.start(audioContext.currentTime);
oscillator.stop(audioContext.currentTime + 0.5);
};
// Function to create a snare drum sound
const playSnareDrumSound = (volume = NORMAL_VOLUME) => {
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();
oscillator.type = 'triangle';
oscillator.frequency.setValueAtTime(200, audioContext.currentTime); // Frequency
gainNode.gain.setValueAtTime(volume, audioContext.currentTime); // Start gain
gainNode.gain.exponentialRampToValueAtTime(0.001, audioContext.currentTime + 0.2); // End gain
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
oscillator.start(audioContext.currentTime);
oscillator.stop(audioContext.currentTime + 0.2);
};
// Function to update button states based on mode
const updateButtonState = (button, isCmdClick) => {
const rowId = button.closest('.row').id;
const states = rowId === 'row-acc' ? ['off', 'on'] : (lightMode || isCmdClick ? lightStates : normalStates);
const currentState = allStates.find(state => button.classList.contains(state));
const currentIndex = states.indexOf(currentState);
const nextIndex = (currentIndex + 1) % states.length;
button.classList.remove(currentState);
button.classList.add(states[nextIndex]);
if (rowId === 'row-acc' && states[nextIndex] === 'on') {
button.classList.add('on-acc');
} else {
button.classList.remove('on-acc');
}
saveButtonStates();
};
// Function to save button states to localStorage
const saveButtonStates = () => {
const buttonStates = {};
rows.forEach(rowId => {
const row = document.getElementById(rowId);
const buttons = row.querySelectorAll('.button');
buttonStates[rowId] = Array.from(buttons).map(button => {
return allStates.find(state => button.classList.contains(state));
});
});
const allPagesStates = JSON.parse(localStorage.getItem('allPagesStates')) || {};
allPagesStates[currentPage] = buttonStates;
localStorage.setItem('allPagesStates', JSON.stringify(allPagesStates));
};
// Function to load button states from localStorage
const loadButtonStates = (page) => {
const allPagesStates = JSON.parse(localStorage.getItem('allPagesStates'));
if (allPagesStates && allPagesStates[page]) {
const buttonStates = allPagesStates[page];
rows.forEach(rowId => {
const row = document.getElementById(rowId);
const buttons = row.querySelectorAll('.button');
buttonStates[rowId].forEach((state, index) => {
const button = buttons[index];
allStates.forEach(s => button.classList.remove(s));
button.classList.add(state);
if (rowId === 'row-acc' && state === 'on') {
button.classList.add('on-acc');
}
});
});
} else {
rows.forEach(rowId => {
const row = document.getElementById(rowId);
const buttons = row.querySelectorAll('.button');
buttons.forEach(button => {
allStates.forEach(state => button.classList.remove(state));
button.classList.add('off');
});
});
}
};
// Function to switch pages
const switchPage = (page) => {
saveButtonStates();
currentPage = page;
loadButtonStates(page);
document.querySelectorAll('.page-button').forEach(button => {
button.classList.remove('active');
});
document.querySelector(`.page-button[data-page="${page}"]`).classList.add('active');
};
// Function to step through the sequence
const stepSequence = () => {
rows.forEach(rowId => {
const row = document.getElementById(rowId);
const buttons = row.querySelectorAll('.button');
const button = buttons[currentStep];
if (!button.classList.contains('off')) {
switch (rowId) {
case 'row-oh':
playOpenHiHatSound();
break;
case 'row-ch':
playClosedHiHatSound();
break;
case 'row-hc':
playHandClapSound();
break;
case 'row-lt':
playLowTomSound();
break;
case 'row-sd':
playSnareDrumSound();
break;
case 'row-bd':
playKickSound();
break;
}
}
button.classList.add('active-step');
});
// Remove the active-step class from the previous step
const previousStep = (currentStep - 1 + 16) % 16;
rows.forEach(rowId => {
const row = document.getElementById(rowId);
const buttons = row.querySelectorAll('.button');
const button = buttons[previousStep];
button.classList.remove('active-step');
});
currentStep = (currentStep + 1) % 16;
};
const playStep = (step) => {
rows.forEach(rowId => {
const row = document.getElementById(rowId);
const buttons = row.querySelectorAll('.button');
buttons.forEach(button => button.classList.remove('active-step'));
const currentButton = buttons[step];
currentButton.classList.add('active-step');
const buttonClasses = Array.from(currentButton.classList);
const isActive = buttonClasses.some(cls =>
['on', 'roll', 'flare', 'light', 'light-roll', 'light-flare'].includes(cls)
);
const isLight = buttonClasses.some(cls =>
['light', 'light-roll', 'light-flare'].includes(cls)
);
const isRoll = buttonClasses.some(cls =>
['roll', 'light-roll'].includes(cls)
);
if (isActive) {
const volume = isLight ? LIGHT_VOLUME : NORMAL_VOLUME;
const stepTime = calculateStepTime(currentBPM);
const playSound = (soundFunction) => {
soundFunction(volume);
if (isRoll) {
setTimeout(() => soundFunction(volume), stepTime / 2);
}
};
switch(rowId) {
case 'row-oh':
playSound(playOpenHiHatSound);
break;
case 'row-ch':
playSound(playClosedHiHatSound);
break;
case 'row-hc':
playSound(playHandClapSound);
break;
case 'row-lt':
playSound(playLowTomSound);
break;
case 'row-sd':
playSound(playSnareDrumSound);
break;
case 'row-bd':
playSound(playKickSound);
break;
case 'row-acc':
playSound(playAccentSound);
break;
}
}
});
};
// Function to start the sequencer
const startSequencer = () => {
isPlaying = true;
const stepTime = calculateStepTime(currentBPM);
currentStep = 0; // Reset step counter
intervalId = setInterval(() => {
playStep(currentStep);
currentStep = (currentStep + 1) % 16;
}, stepTime);
};
// Function to stop the sequencer
const stopSequencer = () => {
isPlaying = false;
clearInterval(intervalId);
currentStep = 0;
// Clear active step indicators
rows.forEach(rowId => {
const row = document.getElementById(rowId);
const buttons = row.querySelectorAll('.button');
buttons.forEach(button => button.classList.remove('active-step'));
});
};
// Add BPM handling
const bpmInput = document.getElementById('bpmInput');
if (bpmInput) {
bpmInput.value = currentBPM;
bpmInput.addEventListener('input', (e) => {
let value = parseFloat(e.target.value);
// Validate and constrain BPM
if (isNaN(value) || value < 20) value = 20;
if (value > 300) value = 300;
value = Math.round(value * 100) / 100; // Round to 2 decimal places
currentBPM = value;
localStorage.setItem('sequencerBPM', value);
// If sequencer is playing, restart it with new tempo
if (isPlaying) {
stopSequencer();
startSequencer();
}
});
}
// Initialize buttons and add event listeners
rows.forEach((rowId) => {
const row = document.getElementById(rowId);
const buttonsContainer = row.querySelector('.buttons');
for (let i = 0; i < 16; i++) {
const button = document.createElement('div');
button.classList.add('button', 'off');
button.dataset.column = i; // Add a data attribute to identify the column
button.addEventListener('click', (event) => {
updateButtonState(button, event.metaKey || event.ctrlKey);
});
buttonsContainer.appendChild(button);
// Add a divider after every 4 buttons
if ((i + 1) % 4 === 0 && i !== 15) {
const divider = document.createElement('div');
divider.classList.add('divider');
buttonsContainer.appendChild(divider);
}
}
// Add event listener for row reset button
const resetRowButton = row.querySelector('.reset-row');
resetRowButton.addEventListener('click', () => {
const buttons = buttonsContainer.querySelectorAll('.button');
buttons.forEach(button => {
allStates.forEach(state => button.classList.remove(state));
button.classList.add('off');
});
saveButtonStates();
});
});
// Add event listeners for column reset buttons
const resetColumnButtons = document.querySelectorAll('.reset-column');
resetColumnButtons.forEach(resetColumnButton => {
resetColumnButton.addEventListener('click', () => {
const columnIndex = resetColumnButton.dataset.column;
rows.forEach(rowId => {
const row = document.getElementById(rowId);
const button = row.querySelector(`.buttons .button[data-column="${columnIndex}"]`);
if (button) {
allStates.forEach(state => button.classList.remove(state));
button.classList.add('off');
}
});
saveButtonStates();
});
});
// Reset pattern button functionality
const resetButton = document.getElementById('reset-pattern');
resetButton.addEventListener('click', () => {
const buttons = document.querySelectorAll('.button');
buttons.forEach(button => {
allStates.forEach(state => button.classList.remove(state));
button.classList.add('off');
});
saveButtonStates();
});
// Light mode toggle functionality
const lightModeToggle = document.getElementById('light-mode-toggle');
lightModeToggle.addEventListener('change', (event) => {
lightMode = event.target.checked;
});
// Page buttons functionality
const pageButtons = document.querySelectorAll('.page-button');
pageButtons.forEach(button => {
button.addEventListener('click', () => {
switchPage(parseInt(button.dataset.page));
});
});
// Play/Pause button functionality
const playPauseButton = document.getElementById('play-pause');
if (playPauseButton) {
playPauseButton.addEventListener('click', () => {
initAudio();
if (isPlaying) {
stopSequencer();
playPauseButton.textContent = 'Play';
} else {
startSequencer();
playPauseButton.textContent = 'Pause';
}
});
}
// Load button states on page load
loadButtonStates(currentPage);
document.querySelector(`.page-button[data-page="${currentPage}"]`).classList.add('active');
});