forked from momentollogy/ArduinoPianoBuzzerSongCreator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
1006 lines (791 loc) · 25.9 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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!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;
font-weight: bold;
cursor: pointer;
position: relative;
line-height:150px; /* Adjust this value */
}
.black::before {
content: attr(data-key);
position: absolute;
top: 40%; /* Adjust this value to move black key text up or down */
left: 50%;
transform: translate(-50%, -50%);
color: white;
font-size: 8px; /*black keys */
}
.white.pressed {
background-color: #ccc;
}
.black.pressed {
background-color: #333;
}
input[type=range] {
width: 6.6%; /* Adjusts the slider width */
}
#slider-container {
position: relative;
display: inline-block;
}
#slider-container:hover::after {
content: "SLIDER CONTROL \A \A Use the quantization slider to remove certain note durations while recording. \A \A Left (default): Full range of note durations. (32nd, 16th, 8th, 4th, 1/2, and whole notes) \A \A Middle: Excludes 32nd notes (longest note duration is a 16th). \A \A Right: Excludes 32nd and 16th (longest note duration is an 8th note). \A \A Typically stay on the default but if your song plays back too fast in parts, try removing the faster notes for better playback. \A \A * Rest durations are unaffected by the slider. \A \A Watch tutorial for detailed explanation.";
display: block;
position: absolute;
bottom: -300px;
left: 0;
width: 300px;
background-color: white;
color: black;
text-align: left;
border: 1px solid #aaa;
padding: 10px;
font-size: 12px;
line-height: 1.4;
white-space: pre-wrap;
width: 670%; /* Change this to 100% */
max-width: 475px; /* Add this line */
z-index: 1000;
}
#slider-container:not(:hover)::after {
content: "";
}
/* mobile.css */
@media screen and (max-width: 767px) {
/* Container for the piano keys */
.piano {
position: relative;
overflow-x: scroll;
overflow-y: hidden;
width: 100%;
height: 150px;
white-space: nowrap;
}
/* Adjust the style of the white keys */
.white-key {
width: 25px;
height: 140px;
border: 1px solid #000;
background-color: #fff;
box-shadow: 0 0 3px rgba(0, 0, 0, 0.2);
}
/* Adjust the style of the black keys */
.black-key {
width: 18px;
height: 90px;
border: 1px solid #000;
background-color: #000;
box-shadow: 0 0 3px rgba(0, 0, 0, 0.2);
z-index: 2;
}
/* Hide the metronome UI */
.metronome {
display: none;
}
/* Show the metronome dropdown */
.metronome-dropdown {
display: block;
}
/* Adjust the size and position of the record button */
.record {
position: absolute;
bottom: 10px;
left: 20px;
width: 40px;
height: 40px;
}
/* Adjust the size and position of the stop button */
.stop {
position: absolute;
bottom: 10px;
right: 20px;
width: 40px;
height: 40px;
}
}
</style>
<link rel="stylesheet" href="mobile.css">
</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="192">`</div>
<div class="key black" data-note="49" data-key="1">1</div>
<div class="key white" data-note="81">Q</div>
<div class="key white" data-note="65">A</div>
<div class="key black" data-note="87" data-key="W">W</div>
<div class="key white" data-note="83">S</div>
<div class="key black" data-note="69" data-key="E">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" data-key="T">T</div>
<div class="key white" data-note="71">G</div>
<div class="key black" data-note="89" data-key="Y">Y</div>
<div class="key white" data-note="72">H</div>
<div class="key black" data-note="85" data-key="U">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" data-key="O">O</div>
<div class="key white" data-note="76">L</div>
<div class="key black" data-note="80" data-key="P">P</div>
<div class="key white" data-note="59">;</div>
<div class="key white" data-note="222">'</div>
<div class="key black" data-note="221" data-key="[">]</div>
<div class="key white" data-note="220">\</div>
</div>
<!-- RECORD and PLAYBACK BUTTONS -->
<input type="text" id="song-title" placeholder="Enter song title" style="display: none;"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>
<label for="playback-tempo">Playback Tempo:</label>
<input type="number" id="playback-tempo" name="playback-tempo" min="40" max="240" value="92" step="1">
<!-- SLIDER BUTTON -->
<div id="slider-container">
<input type="range" min="0" max="2" step="1" value="0" id="slider" style="width: 82px;" oninput="updateSliderValue(this.value)">
</div>
<!-- METRONOME BUTTONS + post recording buttons -->
<label for="metronome-bpm">Metronome BPM: </label>
<!-- Mobile metronome drop-down menu -->
<div class="metronome-dropdown-mobile">
<label for="metronome-mobile">Metronome:</label>
<select id="metronome-mobile" name="metronome-mobile">
<option value="40">40 BPM</option>
<option value="60">60 BPM</option>
<option value="80">80 BPM</option>
<option value="100">100 BPM</option>
<option value="120">120 BPM</option>
<option value="140">140 BPM</option>
<option value="160">160 BPM</option>
<option value="180">180 BPM</option>
<option value="200">200 BPM</option>
</select>
</div>
<!-- End of mobile metronome drop-down menu -->
<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>
<button id="copySongBtn" style="display: none;" onclick="copySongToClipboard(songString)">Copy Song</button>
<br> <br> <br> <br>
<!-- LINKS -->
<div>
<a href="https://www.youtube.com/watch?v=O1d9LQ68KAs" target="_blank">Watch Tutorial</a>
</div>
<br>
<a href="https://drive.google.com/file/d/1yrtmyYl0rtv1ygd7zXIvFQ-BlhMG3M76/view?usp=share_link" download target="_blank">
Download Arduino IDE Code
</a>
</p>
<!-- LOAD ARRAY TEXTAREA UI -->
<div style="position: absolute; right: 0px; top: 116px; padding-right: 500px;">
<textarea id="songInput" placeholder="Paste song array" style="width: 288px; height: 145px;
overflow: auto; text-align: center;"></textarea>
<br>
<button onclick="window.open('https://docs.google.com/spreadsheets/d/1C9cqSvijRkJepxErd_jL0HQ4PCrjC0h7arOYj41DDOg/edit#gid=0', '_blank');">Browse/Save To Library</button>
<button id="loadSongButton" onclick="loadSongFromInput()">Load Song</button>
<button id="clearArray" onclick="clearSongArray()">Clear</button>
</div>
<script>
function updateSliderValue(value) {
sliderValue = parseInt(value);
}
// Create a Web Audio API context
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
// Frequencies for the piano keys (C4 to C5)
const frequencies = {
192: 220.00, // ` (next to the 1 key)
49: 233.08, // 1
81: 246.94, // Q
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, // ;
221: 739.99, // ]
220: 783.99, // \
};
const noteNames = {
220.00: "NOTE_A3",
233.08: "NOTE_As3",
246.94: "NOTE_B3",
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",
739.99: "NOTE_Fs5",
783.99: "NOTE_G5",
};
//THIS IS TO map the note names to the key codes for load button.
const noteToKeyCode = {
'NOTE_A3': 192,
'NOTE_As3': 49,
'NOTE_B3': 81,
'NOTE_C4': 65,
'NOTE_Cs4': 87,
'NOTE_D4': 83,
'NOTE_Ds4': 69,
'NOTE_E4': 68,
'NOTE_F4': 70,
'NOTE_Fs4': 84,
'NOTE_G4': 71,
'NOTE_Gs4': 89,
'NOTE_A4': 72,
'NOTE_As4': 85,
'NOTE_B4': 74,
'NOTE_C5': 75,
'NOTE_Cs5': 79,
'NOTE_D5': 76,
'NOTE_Ds5': 80,
'NOTE_E5': 59,
'NOTE_F5': 222,
'NOTE_Fs5': 221,
'NOTE_G5': 220,
};
//Makes blackkeynames work
const keyNames = {
49: '1',
81: 'Q',
87: 'W',
69: 'E',
84: 'T',
89: 'Y',
85: 'U',
79: 'O',
80: 'P',
221: ']',
};
document.querySelectorAll('.key.black').forEach((key) => {
const keyCode = key.getAttribute('data-note');
key.innerText = keyNames[keyCode] || key.innerText;
});
let playingNotes = new Set();
let sliderValue = 0.5;
function updateSliderValue(value) {
sliderValue = parseFloat(value);
}
// Map DURATION TO NOTE LENGTH
function mapDurationToNoteLength(duration, isRest) {
const noteLengths = {
108: "NOTE_THIRTY_SECOND",
216: "NOTE_SIXTEENTH",
324: "NOTE_EIGHTH",
486: "NOTE_DOTTED_EIGHTH",
648: "NOTE_QUARTER",
972: "NOTE_DOTTED_QUARTER",
1296: "NOTE_HALF",
2592: "NOTE_WHOLE",
};
if (!isRest) {
if (sliderValue >= 1) {
delete noteLengths[108]; // Remove 32nd notes based on the slider value
}
if (sliderValue >= 2) {
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 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);
return oscillator;
}
let isPlaying = false;
// Play event listener
document.getElementById('play').addEventListener('click', async () => {
if (isPlaying) return;
isPlaying = true;
document.getElementById('stop').disabled = false;
await playRecordedNotes(recordedNotes).then(() => {
document.getElementById('stop').disabled = true;
isPlaying = false;
});
});
let currentOscillator = null; // Add this line
// Play and record function
function playAndRecord(frequency, keyElement) {
const playAndRecordCallback = (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 });
}
recordedNotes.push({
frequency: frequency,
duration: duration,
startTime: new Date().getTime()
});
recordingStartTime = new Date().getTime();
}
};
if (recordingNote) {
const currentKeyCode = Array.from(playingNotes)[0];
const currentKeyElement = document.querySelector(`.key[data-note="${currentKeyCode}"]`);
if (currentKeyElement) {
currentKeyElement.dispatchEvent(new MouseEvent('mouseup'));
}
}
playNote(frequency, keyElement, playAndRecordCallback);
recordingNote = true;
}
// PLAYRECORDED NOTES FUNCTION
async function playRecordedNotes(notes) {
stopPlaybackRequested = false;
const timeBetweenNotesMs = 0;
const playbackTempo = parseInt(document.getElementById("playback-tempo").value);
const tempoFactor = 92.6 / playbackTempo; // Calculate the tempo factor based on the default BPM (92.6) and the playback tempo
// Disable the "Play" button while the song is playing
const playButton = document.getElementById('play');
playButton.disabled = true;
for (const note of notes) {
if (stopPlaybackRequested) {
break;
}
if (note.rest) {
const restDurationMs = noteLengthsMs[mapDurationToNoteLength(note.duration, true)];
await new Promise(resolve => setTimeout(resolve, restDurationMs * tempoFactor + 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, () => {
if (stopPlaybackRequested) {
oscillator.stop();
}
});
playbackOscillators.push(oscillator);
const noteDurationMs = noteLengthsMs[mapDurationToNoteLength(note.duration, false)];
await new Promise(resolve => {
const timeout = setTimeout(() => {
if (!stopPlaybackRequested) {
oscillator.stop();
keyElement.classList.remove("pressed");
}
resolve();
}, noteDurationMs * tempoFactor - 50);
playbackTimeouts.push(timeout);
});
await new Promise(resolve => setTimeout(resolve, timeBetweenNotesMs));
}
}
// Re-enable the "Play" button when the song stops playing
playButton.disabled = false;
}
function releaseAllKeys() {
const pianoKeys = document.querySelectorAll('.key.pressed');
pianoKeys.forEach(key => {
key.classList.remove('pressed');
});
}
function stopPlayback() {
stopPlaybackRequested = true;
// Clear all timeouts
for (const timeout of playbackTimeouts) {
clearTimeout(timeout);
}
// Stop all oscillators
for (const oscillator of playbackOscillators) {
oscillator.stop();
}
// Reset arrays
playbackTimeouts = [];
playbackOscillators = [];
isPlaying = false; // Add this line
// Release all pressed keys
releaseAllKeys();
}
//event listner for mouse click on keys
const pianoKeys = document.querySelectorAll('.key');
pianoKeys.forEach(key => {
key.addEventListener('mousedown', () => {
const keyCode = key.dataset.note;
if (!playingNotes.has(keyCode)) {
playingNotes.add(keyCode);
playAndRecord(frequencies[keyCode], key);
}
});
key.addEventListener('mousemove', (event) => {
if (event.buttons === 1) { // Check if the left mouse button is pressed
const keyCode = key.dataset.note;
if (!playingNotes.has(keyCode)) {
playingNotes.add(keyCode);
playAndRecord(frequencies[keyCode], key);
}
}
});
key.addEventListener('mouseleave', () => {
const keyCode = key.dataset.note;
if (playingNotes.has(keyCode)) {
playingNotes.delete(keyCode);
key.dispatchEvent(new MouseEvent('mouseup'));
}
});
});
//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 = [];
recordingStartTime = null;
document.getElementById('record').disabled = true;
document.getElementById('stop').disabled = false;
});
function stopPlayback() {
stopPlaybackRequested = true;
// Clear all timeouts
for (const timeout of playbackTimeouts) {
clearTimeout(timeout);
}
// Stop all oscillators
for (const oscillator of playbackOscillators) {
oscillator.stop();
}
// Reset arrays
playbackTimeouts = [];
playbackOscillators = [];
isPlaying = false; // Add this line
}
// Stop recording
document.getElementById('stop').addEventListener('click', () => {
recording = false;
startTime = null;
document.getElementById('record').disabled = false;
document.getElementById('stop').disabled = true;
displayRecording();
stopMetronome();
// Call stopPlayback() if either recording or playing
if (recording || isPlaying) {
stopPlayback();
document.getElementById('play').disabled = false;
}
});
// Clear button
document.getElementById('clear').addEventListener('click', () => {
recordedNotes = [];
document.getElementById("recording").innerHTML = "";
});
// Rest function
function addRest() {
if (recording) {
const currentTime = new Date().getTime();
const restDuration = currentTime - recordingStartTime;
if (restDuration >= 100) {
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'));
}
});
// Display recording function
function displayRecording() {
let output = "";
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 += "};";
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));
}
function getKeyCodeForFrequency(frequency) {
for (const [keyCode, freq] of Object.entries(frequencies)) {
if (freq === frequency) {
return keyCode;
}
}
return null;
}
let playbackTimeouts = [];
let playbackOscillators = [];
const noteLengthsMs = {
"NOTE_THIRTY_SECOND": 108,
"NOTE_SIXTEENTH": 216,
"NOTE_EIGHTH": 324,
"NOTE_DOTTED_EIGHTH": 486,
"NOTE_QUARTER": 648,
"NOTE_DOTTED_QUARTER": 972,
"NOTE_HALF": 1296,
"NOTE_WHOLE": 2592,
};
// LOAD SONG EVENT LISTENER
document.getElementById('loadSongButton').addEventListener('click', loadSongFromInput);
// LOAD SONG FUNCTION
function loadSongFromInput() {
const songString = document.getElementById('songInput').value;
console.log('Song string:', songString);
const regex = /{([^}]+)}/g;
const rawSongData = songString.match(regex);
if (!rawSongData) {
alert('Invalid song format. Please make sure the input is correct.');
return;
}
const songArray = rawSongData.map((item) => {
const cleanedItem = item.replace(/[{}]/g, '');
const values = cleanedItem.split(',').map((val) => val.trim());
return [values[0], values[1]];
});
console.log('Song array:', songArray);
const loadedSong = songArray.map(([note, duration]) => {
const keyCode = noteToKeyCode[note];
const noteDuration = noteLengthsMs[duration];
return {
frequency: note === '0' ? 0 : frequencies[keyCode],
duration: noteDuration,
durationString: duration,
rest: note === '0',
};
});
console.log('Loaded song:', loadedSong);
displayLoadedSong(loadedSong);
recordedNotes = loadedSong; // Update the recordedNotes with the loaded song data
}
//CLEAR ARRAY
function clearSongArray() {
document.getElementById('songInput').value = '';
}
//DISPLAY LOADED SONG FUNCTION
function displayLoadedSong(songArray) {
let output = "";
const songTitle = document.getElementById("song-title").value;
const notesCount = songArray.length;
output += `${songTitle}[${notesCount}][2] =\n{\n`;
songArray.forEach((noteObject) => {
const note = noteObject.rest ? '0' : noteNames[noteObject.frequency];
const duration = noteObject.durationString; // Use the original duration string
output += ` {${note}, ${duration}},\n`;
});
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));
}
//QUANTIZE STUFF
function closestDuration(duration, supportedDurations) {
return supportedDurations.reduce((prev, curr) =>
Math.abs(curr - duration) < Math.abs(prev - duration) ? curr : prev
);
}
function quantizeNoteDuration(duration) {
const supportedDurations = [108, 216, 324, 486, 648, 972, 1296, 2592];
return closestDuration(duration, supportedDurations);
}
function quantizeRestDuration(duration) {
const supportedDurations = [108, 216, 324, 486, 648, 972, 1296, 2592];
return closestDuration(duration, supportedDurations);
}
// Example usage
let noteDuration = 0.37; // Example note duration value
let quantizedNoteDuration = quantizeNoteDuration(noteDuration);
console.log(quantizedNoteDuration); // output: 324 (closest to an eighth note)
let restDuration = 0.185; // Example rest duration value
let quantizedRestDuration = quantizeRestDuration(restDuration);
console.log(quantizedRestDuration); // output: 216 (closest to a sixteenth note)
//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;
// Disable the "Start Metronome" button when the metronome starts
const startMetronomeButton = document.getElementById('start-metronome');
startMetronomeButton.disabled = true;
metronomeInterval = setInterval(() => {
const whiteNoiseSource = createWhiteNoise();
const gainNode = audioContext.createGain();
gainNode.gain.value = 0.2;
const filterNode = audioContext.createBiquadFilter();
filterNode.type = 'bandpass';
filterNode.frequency.value = 2000;
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;
}
// Re-enable the "Start Metronome" button when the metronome stops
const startMetronomeButton = document.getElementById('start-metronome');
startMetronomeButton.disabled = false;
}
//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();
});
//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>
<!-- Default Statcounter code for Arduino Buzzer Song
Creator
https://momentollogy.github.io/ArduinoPianoBuzzerSongCreator/
-->
<script type="text/javascript">
var sc_project=12871653;
var sc_invisible=1;
var sc_security="8887c24b";
</script>
<script type="text/javascript"
src="https://www.statcounter.com/counter/counter.js"
async></script>
<noscript><div class="statcounter"><a title="Web Analytics
Made Easy - Statcounter" href="https://statcounter.com/"
target="_blank"><img class="statcounter"
src="https://c.statcounter.com/12871653/0/8887c24b/1/"