forked from momentollogy/ArduinoPianoBuzzerSongCreator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
602 lines (481 loc) · 16.6 KB
/
index.html
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Arduino Piano Buzzer Song Creator</title>
<style>
body {
font-family: Arial, sans-serif;
}
.white {
display: inline-block;
background-color: white;
border: 1px solid black;
height: 150px;
width: 50px;
text-align: center;
line-height: 150px;
font-weight: bold;
cursor: pointer;
}
.black {
display: inline-block;
background-color: black;
border: 1px solid black;
height: 100px;
width: 30px;
margin-left: -20px;
margin-right: -20px;
z-index: 1;
text-align: center;
line-height: 100px;
font-weight: bold;
cursor: pointer;
}
.white.pressed {
background-color: #ccc;
}
.black.pressed {
background-color: #333;
}
</style>
<script src="https://apis.google.com/js/api.js"></script>
<script src="https://apis.google.com/js/platform.js" async defer></script>
<meta name="google-signin-client_id" content="303614643987-2au0ltghltd0u2vk7g36t3ofmtf63vos.apps.googleusercontent.com">
</head>
<body>
<h1>Arduino Piano Buzzer Song Creator V1 <br> <small>by momentollogy</small><br></h1>
<div id="piano">
<div class="key white" data-note="65">A</div>
<div class="key black" data-note="87">W</div>
<div class="key white" data-note="83">S</div>
<div class="key black" data-note="69">E</div>
<div class="key white" data-note="68">D</div>
<div class="key white" data-note="70">F</div>
<div class="key black" data-note="84">T</div>
<div class="key white" data-note="71">G</div>
<div class="key black" data-note="89">Y</div>
<div class="key white" data-note="72">H</div>
<div class="key black" data-note="85">U</div>
<div class="key white" data-note="74">J</div>
<div class="key white" data-note="75">K</div>
<div class="key black" data-note="79">O</div>
<div class="key white" data-note="76">L</div>
<div class="key black" data-note="80">P</div>
<div class="key white" data-note="59">;</div>
<div class="key white" data-note="222">'</div>
</div>
<!-- ... existing HTML code ... -->
<div id="piano">
<!-- ... piano keys ... -->
</div>
<input type="text" id="song-title" placeholder="Enter song title" value="int Untitled_Song_1" />
<button id="record">Record</button>
<button id="stop" disabled>Stop</button>
<button id="clear">Clear</button>
<button id="play" onclick="playSongArray()">Play</button>
<input type="range" min="0" max="1" step="0.01" value="0.5" id="slider" oninput="updateSliderValue(this.value)">
<label for="metronome-bpm">Metronome BPM: </label>
<input type="number" id="metronome-bpm" value="120" min="40" max="240" />
<button id="start-metronome">Start</button>
<button id="stop-metronome">Stop</button>
<div id="recording"></div>
<!-- ... existing script tag ... -->
<div class="g-signin2" data-onsuccess="onSignIn"></div>
<button onclick="signOut()">Sign out</button>
<button id="copySongBtn" style="display: none;" onclick="copySongToClipboard(songString)">Copy Song</button>
<div>
<a href="https://www.youtube.com/watch?v=-HBDiNoQkAw">Watch Tutorial</a>
</div>
<br>
<a href="https://drive.google.com/file/d/1yrtmyYl0rtv1ygd7zXIvFQ-BlhMG3M76/view?usp=share_link" download>
Download Arduino IDE Code
</a>
</p>
<a href="https://drive.google.com/file/d/1SWQt95t4wXOxO6g63XlXmQHOSjGSYQOA/view?usp=share_link" download>
Download HTML/JAVA
</a>
</p>
<script>
// API STUFF
function onSignIn(googleUser) {
const token = googleUser.getAuthResponse().id_token;
gapi.load('client', () => initClient(token));
}
function signOut() {
const auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(() => {
console.log('User signed out.');
gapi.client = null;
});
}
function initClient(token) {
gapi.client.init({
apiKey: 'AIzaSyA90ftyrgjmJPfzKeXYypzBdO9IJlbHU78',
clientId: '303614643987-2au0ltghltd0u2vk7g36t3ofmtf63vos.apps.googleusercontent.com',
discoveryDocs: ['https://sheets.googleapis.com/$discovery/rest?version=v4'],
scope: 'https://www.googleapis.com/auth/spreadsheets',
idToken: token,
}).then(() => {
console.log('Client initialized.');
// Call functions that require authenticated access to the API here
}, error => {
console.error('Error initializing client:', error);
});
}
let sliderValue = 0.5;
function updateSliderValue(value) {
sliderValue = parseFloat(value);
}
// Create a Web Audio API context
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
// Frequencies for the piano keys (C4 to C5)
const frequencies = {
65: 261.63, // A
87: 277.18, // W
83: 293.66, // S
69: 311.13, // E
68: 329.63, // D
70: 349.23, // F
84: 369.99, // T
71: 392.00, // G
89: 415.30, // Y
72: 440.00, // H
85: 466.16, // U
74: 493.88, // J
75: 523.25, // K
79: 554.37, // O
76: 587.33, // L
80: 622.25, // P
59: 659.26, // ;
222: 698.26, // ;
};
const noteNames = {
261.63: "NOTE_C4",
277.18: "NOTE_Cs4",
293.66: "NOTE_D4",
311.13: "NOTE_Ds4",
329.63: "NOTE_E4",
349.23: "NOTE_F4",
369.99: "NOTE_Fs4",
392.00: "NOTE_G4",
415.30: "NOTE_Gs4",
440.00: "NOTE_A4",
466.16: "NOTE_As4",
493.88: "NOTE_B4",
523.25: "NOTE_C5",
554.37: "NOTE_Cs5",
587.33: "NOTE_D5",
622.25: "NOTE_Ds5",
659.26: "NOTE_E5",
698.26: "NOTE_F5",
};
let playingNotes = new Set();
// Map DURATION TO NOTE LENGTH
function mapDurationToNoteLength(duration, isRest) {
const noteLengths = {
108: "NOTE_THIRTY_SECOND",
216: "NOTE_SIXTEENTH",
324: "NOTE_EIGHTH",
648: "NOTE_QUARTER",
1296: "NOTE_HALF",
2592: "NOTE_WHOLE",
};
if (!isRest) {
if (sliderValue >= 0.5) {
delete noteLengths[108]; // Remove 32nd notes based on the slider value
}
if (sliderValue >= 1) {
delete noteLengths[216]; // Remove 16th notes based on the slider value
}
}
let closestDuration = Object.keys(noteLengths).reduce((prev, curr) => {
return Math.abs(curr - duration) < Math.abs(prev - duration) ? curr : prev;
});
return noteLengths[closestDuration];
}
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
// Function to play a note
function playNote(frequency, keyElement, onStop) {
const oscillator = audioContext.createOscillator();
oscillator.type = 'sine'; // Wave type
oscillator.frequency.value = frequency;
oscillator.connect(audioContext.destination);
oscillator.start();
const startTime = audioContext.currentTime * 1000;
// Add the pressed state for the key
keyElement.classList.add('pressed');
const handleMouseUp = () => {
oscillator.stop();
keyElement.classList.remove('pressed');
keyElement.removeEventListener('mouseup', handleMouseUp);
const duration = (audioContext.currentTime * 1000) - startTime;
playingNotes.delete(Number(keyElement.dataset.note)); // remove key code from playingNotes Set
recordingNote = false; // reset recordingNote flag
if (onStop) onStop(duration);
};
keyElement.addEventListener('mouseup', handleMouseUp);
// Add the return statement here
return oscillator;
}
//Funtion to add a rest
function addRestIfNeeded() {
if (recordedNotes.length > 1) {
const previousNote = recordedNotes[recordedNotes.length - 2];
const restDuration = (recordedNotes[recordedNotes.length - 1].startTime) - (previousNote.startTime + previousNote.duration);
if (restDuration > 0) {
recordedNotes.splice(recordedNotes.length - 1, 0, { rest: true, duration: restDuration });
}
}
}
let recording = false;
let playing = false;
let startTime = null;
let recordedNotes = [];
let recordingNote = false;
let recordingStartTime;
// Start recording
document.getElementById('record').addEventListener('click', () => {
recording = true;
startTime = Date.now();
recordedNotes = []; // Clear the recordedNotes array before starting a new recording
recordingStartTime = null; // Reset the recordingStartTime
document.getElementById('record').disabled = true;
document.getElementById('stop').disabled = false;
});
// Stop recording
document.getElementById('stop').addEventListener('click', () => {
recording = false;
startTime = null;
document.getElementById('record').disabled = false;
document.getElementById('stop').disabled = true;
displayRecording();
stopMetronome(); // Add this line to stop the metronome when stopping the recording
});
//Clear button
document.getElementById('clear').addEventListener('click', () => {
recordedNotes = [];
document.getElementById("recording").innerHTML = "";
});
//PLAY AND RECORD FUNCTIONs
function playAndRecord(frequency, keyElement) {
if (!recordingNote) {
playNote(frequency, keyElement, duration => {
recordingNote = false;
if (recording) {
if (!recordingStartTime) {
recordingStartTime = new Date().getTime();
}
const restDuration = (new Date().getTime() - recordingStartTime) - duration;
if (restDuration > 0) {
recordedNotes.push({
rest: true,
duration: restDuration
});
console.log("Rest added:", { rest: true, duration: restDuration }); // Add this line
}
recordedNotes.push({
frequency: frequency,
duration: duration,
startTime: new Date().getTime() // Add this line
});
console.log("Note added:", { frequency: frequency, duration: duration, startTime: new Date().getTime() }); // Add this line
recordingStartTime = new Date().getTime();
}
});
recordingNote = true;
}
}
//REST FUNCTION
function addRest() {
if (recording) {
const currentTime = new Date().getTime();
const restDuration = currentTime - recordingStartTime;
if (restDuration >= 100) { // Minimum rest duration, you can adjust this value
recordedNotes.push({
rest: true,
duration: restDuration,
});
}
recordingStartTime = currentTime;
}
}
const keyCodes = {
"Semicolon": 59,
'Quote': 222, // "'"
};
document.addEventListener('keydown', event => {
const keyCode = keyCodes[event.code] || event.keyCode;
const keyElement = document.querySelector(`.key[data-note="${keyCode}"]`);
if (keyElement && !playingNotes.has(keyCode)) {
playingNotes.add(keyCode);
playAndRecord(frequencies[keyCode], keyElement);
}
});
document.addEventListener('keyup', event => {
const keyCode = keyCodes[event.code] || event.keyCode;
const keyElement = document.querySelector(`.key[data-note="${keyCode}"]`);
if (keyElement) {
playingNotes.delete(keyCode);
keyElement.dispatchEvent(new MouseEvent('mouseup'));
}
});
// FUNCTION DISPLAYRECORDING
function displayRecording() {
let output = "";
let songArray = "";
const songTitle = document.getElementById("song-title").value;
const notesCount = recordedNotes.length;
output += `${songTitle}[${notesCount}][2] =\n{\n`;
recordedNotes.forEach((note, index) => {
if (note.rest) {
output += ` {0, ${mapDurationToNoteLength(note.duration, true)}},\n`;
} else {
output += ` {${noteNames[note.frequency]}, ${mapDurationToNoteLength(note.duration)}},\n`;
}
});
output += "};";
songArray = output;
const recordingElement = document.getElementById("recording");
recordingElement.innerHTML = `<button id="copy-song">Copy Song</button><pre>${output}</pre>`;
const copySongButton = document.getElementById("copy-song");
copySongButton.addEventListener("click", () => copySongToClipboard(output));
}
//METRONOME STUFF
let metronomeInterval = null;
function createWhiteNoise() {
const bufferSize = 4096;
const buffer = audioContext.createBuffer(1, bufferSize, audioContext.sampleRate);
const output = buffer.getChannelData(0);
for (let i = 0; i < bufferSize; i++) {
output[i] = Math.random() * 2 - 1;
}
const whiteNoiseSource = audioContext.createBufferSource();
whiteNoiseSource.buffer = buffer;
whiteNoiseSource.loop = true;
return whiteNoiseSource;
}
function startMetronome(bpm) {
const interval = 60 / bpm * 1000;
metronomeInterval = setInterval(() => {
const whiteNoiseSource = createWhiteNoise();
const gainNode = audioContext.createGain();
gainNode.gain.value = 0.2; // Adjust the volume of the click sound
const filterNode = audioContext.createBiquadFilter();
filterNode.type = 'bandpass';
filterNode.frequency.value = 2000; // Adjust the pitch of the click sound
filterNode.Q.value = 0.5;
whiteNoiseSource.connect(gainNode);
gainNode.connect(filterNode);
filterNode.connect(audioContext.destination);
whiteNoiseSource.start();
setTimeout(() => {
whiteNoiseSource.stop();
}, 50);
}, interval);
}
function stopMetronome() {
if (metronomeInterval) {
clearInterval(metronomeInterval);
metronomeInterval = null;
}
}
//METRONOME EVENT LISTENER
document.getElementById("start-metronome").addEventListener("click", () => {
const bpm = parseInt(document.getElementById("metronome-bpm").value, 10);
startMetronome(bpm);
});
document.getElementById("stop-metronome").addEventListener("click", () => {
stopMetronome();
});
//PLAY EVENT LISTENER
document.getElementById('play').addEventListener('click', () => {
if (!playing) {
playRecordedNotes(recordedNotes);
}
});
function getKeyCodeForFrequency(frequency) {
for (const [keyCode, freq] of Object.entries(frequencies)) {
if (freq === frequency) {
return keyCode;
}
}
return null;
}
async function playRecordedNotes(notes) {
const timeBetweenNotesMs = 50;
for (const note of notes) {
console.log('Playing note:', note);
if (note.rest) {
console.log(`Waiting (rest) for ${note.duration}ms`);
await new Promise(resolve => setTimeout(resolve, note.duration + timeBetweenNotesMs));
} else {
const keyElement = document.querySelector(`.key[data-note="${getKeyCodeForFrequency(note.frequency)}"]`);
if (!keyElement) {
console.error('Could not find key element for note:', note);
continue;
}
const oscillator = playNote(note.frequency, keyElement);
const duration = parseInt(note.duration); // Parse the recorded note duration as integer
await new Promise(resolve => setTimeout(() => {
console.log('Stopping note:', note);
oscillator.stop(0);
keyElement.classList.remove("pressed");
resolve();
}, duration));
console.log(`Waiting (between notes) for ${timeBetweenNotesMs}ms`);
await new Promise(resolve => setTimeout(resolve, timeBetweenNotesMs));
}
}
}
function quantize(value, step, precision) {
let decimalPlaces = Math.max(0, precision - Math.floor(Math.log10(step)));
let multiplier = Math.pow(10, decimalPlaces);
return Math.round(value / step * multiplier) / multiplier;
}
function quantizeNoteDuration(duration, step, precision) {
return quantize(duration, step, precision);
}
function quantizeRestDuration(duration, step, precision) {
return quantize(duration, step, precision);
}
let value = 10.4567;
let step = 0.1;
let precision = 3;
let quantizedValue = quantize(value, step, precision);
console.log(quantizedValue); // output: 10.5
let noteDuration = 0.37; // Example note duration value
let noteDurationStep = 1 / 16; // Quantize to 16th notes
let noteDurationPrecision = 3;
let quantizedNoteDuration = quantizeNoteDuration(noteDuration, noteDurationStep, noteDurationPrecision);
console.log(quantizedNoteDuration); // output: 0.375
let restDuration = 0.185; // Example rest duration value
let thirtySecondNoteDuration = sixteenthNoteDuration / 2; // Calculate the duration of a 32nd note at 120 BPM
let restDurationStep = thirtySecondNoteDuration; // Use the calculated duration as the quantization step
let restDurationPrecision = 3;
let quantizedRestDuration = quantizeRestDuration(restDuration, restDurationStep, restDurationPrecision);
console.log(quantizedRestDuration); // output: 0.1875
//COPYSONG TO CLIPBOARTD FUNCTION
function copySongToClipboard(songString) {
const songElement = document.createElement('textarea');
songElement.value = songString;
document.body.appendChild(songElement);
songElement.select();
document.execCommand('copy');
document.body.removeChild(songElement);
alert('Song copied to clipboard');
}
</script>
</body>
</html>