-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.ts
842 lines (686 loc) · 17.1 KB
/
script.ts
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
const HELP_CONTENT = `\
// comments start with //
// Play some notes
C C# D D#
E F F# G
G# A5 A#5 B5
// _ for a rest
_ _ _ _
// Octave is 4 by default
C C4 C C4
_ _ _ _
// add ~ to hold notes longer
// following notes will overlap unless you add rests
C~~~ _ _ _ _ _ _ _
G3~~~~~ _ B~~~~ _ D~~~ _ F~ _
C~~~ _ _ _ _ _ _ _
// use - to create chords
G#~~~-B5~~~-E5~~~ ___
F#~~~-B5~~~ ___
G#~~~-C#5~~~-E5~~~ ___
A5~~~-C#5~~~-E5~~~ ___
// Repeat sections by surrounding them with |: and :|
|: A4~~ _ _ F3~~ _ _ G3~~ _ _ C3~~ _ _
C3~~ _ _ G3~~ _ _ A4~~ _ _ F3~~ _ _ :|
// Repeated sections can be nested
|:
|: |: G#-B5-E5 E :| :|
|: |: F#-B5 B :| :|
|: |: G#-C#5-E5 C# :| :|
|: |: A5-C#5-E5 A :| :|
:|
// You can change the wave type
sine
C E G _
sawtooth
C E G _
square
C E G _
triangle
C E G _
// And finally, you can halt the autoplay with a double bar ||
C E G C5
C5 E5 G5 C6 ||
// Click any of the squares to play that note.
sawtooth
C~~~ E~~ G~ B5
F~~~ A5#~~ C5~ E5
G~~~ B5~~ D5~ G6
C5~~~~-E~~~~-G~~~~ _ _ _
sine
C~~~ E~~ G~ B5
F~~~ A5#~~ C5~ E5
G~~~ B5~~ D5~ G6
C5~~~~-E~~~~-G~~~~ _ _ _
// If you don't put a halt at the end, it will loop forever
||
`;
const KEYS = {
A: 1,
'A#': 2,
Bb: 2,
B: 3,
C: 4,
'C#': 5,
Db: 5,
D: 6,
'D#': 7,
Eb: 7,
E: 8,
F: 9,
'F#': 10,
Gb: 10,
G: 11,
'G#': 12,
Ab: 12,
};
interface Voice {
type: 'voice';
voice: Exclude<OscillatorType, 'custom'>;
}
interface Control {
type: 'halt' | 'beginRepeat' | 'endRepeat';
}
interface Note {
key: keyof typeof KEYS;
octave: number;
sustain: number;
}
interface Chord {
type: 'chord';
notes: Note[];
}
interface Rest {
type: 'rest';
}
type Directive = Chord | Rest | Voice | Control;
const noteRegex = /(?<key>[A-G][#b]?)(?<octave>\d+)?(?<sustain>~*)/;
class Player extends EventTarget {
private context: AudioContext | null;
private _notes: Directive[] = [];
get directives() {
return this._notes;
}
set directives(val: Directive[]) {
this._notes = val;
this.dispatchEvent(new Event('notesChange'));
}
private _waveType: Exclude<OscillatorType, 'custom'> = 'sine';
get waveType() {
return this._waveType;
}
set waveType(val: Exclude<OscillatorType, 'custom'>) {
this._waveType = val;
this.dispatchEvent(new Event('waveTypeChange'));
}
private _head: number = -1;
get head() {
return this._head;
}
set head(val: number) {
this._head = val;
this.dispatchEvent(new Event('headChange'));
}
private _bpm: number = 60;
get bpm() {
return this._bpm;
}
set bpm(val: number) {
this._bpm = val;
this.dispatchEvent(new Event('bpmChange'));
}
private _notesPerBeat: number = 2;
public get notesPerBeat() {
return this._notesPerBeat;
}
public set notesPerBeat(val: number) {
this._notesPerBeat = val;
this.dispatchEvent(new Event('notesPerBeatChange'));
this.dispatchEvent(new Event('bpmChange'));
}
msPerNote: number = 400;
constructor() {
super();
this.context = null;
this.addEventListener('bpmChange', () => {
if (this.isAutoplaying()) {
this.beginAutoplay();
}
});
}
private autoplayId: number | null = null;
private beginRepeatIndex: number[] = [];
private endRepeatIndex: number[] = [];
beginAutoplay() {
this.stopAutoplay();
const interval = 60000 / this.bpm / this.notesPerBeat;
if (this.peekNextDirective().type === 'halt') {
this._head++;
}
this.autoplayId = setInterval(() => {
this.processNextBeat();
}, interval);
}
stopAutoplay() {
if (this.autoplayId !== null) {
clearInterval(this.autoplayId);
this.autoplayId = null;
}
}
reset() {
this.stopAutoplay();
this.head = -1;
this.beginRepeatIndex = [];
this.endRepeatIndex = [];
}
isAutoplaying() {
return !!this.autoplayId;
}
getNextDirective() {
this.head = (this.head + 1) % this.directives.length;
return this.directives[this.head];
}
peekNextDirective() {
return this.directives[(this.head + 1) % this.directives.length];
}
processNextDirective(): boolean {
const directive = this.getNextDirective();
switch (directive.type) {
case 'chord':
this.playChord(directive);
//no break;
case 'rest':
return true;
case 'voice':
this.waveType = directive.voice;
return false;
case 'halt':
if (this.isAutoplaying()) {
this.head -= 1;
this.stopAutoplay();
return true;
}
return false;
case 'beginRepeat':
this.beginRepeatIndex.unshift(this.head);
return false;
case 'endRepeat':
if (this.endRepeatIndex.length > 0) {
if (this.endRepeatIndex[0] === this.head) {
this.endRepeatIndex.shift();
this.beginRepeatIndex.shift();
return false;
}
}
if (this.beginRepeatIndex.length === 0) {
return false;
}
this.endRepeatIndex.unshift(this.head);
this.head = this.beginRepeatIndex[0];
return false;
}
}
processNextBeat() {
if (this.directives.length === 0) return;
const head =
(this.head + this.directives.length) % this.directives.length;
while (!this.processNextDirective() && this.head !== head);
}
playChord(chord: Chord) {
chord.notes.forEach((note) => {
this.playNote(note);
});
}
clearRepeats() {
this.beginRepeatIndex = [];
this.endRepeatIndex = [];
}
playNote({
key,
octave,
sustain,
}: {
key: keyof typeof KEYS;
octave: number;
sustain: number;
}) {
if (this.context === null) {
this.context = new AudioContext();
}
const frequency = getFrequency(key, octave);
const oscillator = this.context.createOscillator();
oscillator.frequency.value = frequency;
oscillator.type = this.waveType;
const sustainMs = sustain * this.msPerNote;
const sustainS = sustainMs / 1000;
const envelope = this.createEnvelope(sustainS);
oscillator.connect(envelope.rise);
envelope.fall.connect(this.context.destination);
oscillator.start();
oscillator.stop(this.context.currentTime + sustainS);
oscillator.onended = () => {
oscillator.disconnect();
envelope.rise.disconnect();
envelope.sustain.disconnect();
envelope.fall.disconnect();
};
}
createEnvelope(duration: number) {
if (this.context === null) {
this.context = new AudioContext();
}
const rise = this.context.createGain();
const sustain = this.context.createGain();
const fall = this.context.createGain();
rise.connect(sustain);
sustain.connect(fall);
rise.gain.value = 0;
rise.gain.exponentialRampToValueAtTime(
1,
this.context.currentTime + (0.1 * this.msPerNote) / 1000
);
sustain.gain.value = 1;
fall.gain.exponentialRampToValueAtTime(
0.0001,
this.context.currentTime + duration - (0.2 * this.msPerNote) / 1000
);
return { rise, sustain, fall };
}
}
class PlayerController {
private abortController: AbortController;
static readonly AUTOSAVE_NAME = `song_autosave`;
dispose() {
this.abortController.abort();
}
constructor(
private player: Player,
private songInput: HTMLTextAreaElement,
private autoplayButton: HTMLButtonElement,
private playNextButton: HTMLButtonElement,
private resetButton: HTMLButtonElement,
private bpmInput: HTMLInputElement,
private notesPerBeatInput: HTMLInputElement,
private beatsPerBarInput: HTMLInputElement,
private waveTypeSelect: HTMLSelectElement,
private notesContainer: HTMLDivElement,
private loadHelpContentButton: HTMLButtonElement
) {
this.abortController = new AbortController();
this.loadHelpContentButton.addEventListener(
'click',
() => {
if (
confirm('This will reset your current song. Are you sure?')
) {
this.setSong(HELP_CONTENT);
}
},
{ signal: this.abortController.signal }
);
this.songInput.addEventListener(
'input',
() => {
localStorage.setItem(
PlayerController.AUTOSAVE_NAME,
this.songInput.value
);
this.setSong(this.songInput.value);
},
{ signal: this.abortController.signal }
);
this.player.addEventListener(
'notesChange',
() => {
this.renderNotes();
},
{ signal: this.abortController.signal }
);
this.player.addEventListener(
'headChange',
() => {
this.renderNotes();
},
{ signal: this.abortController.signal }
);
this.autoplayButton.addEventListener(
'click',
() => {
this.toggleAutoplay();
},
{ signal: this.abortController.signal }
);
this.playNextButton.addEventListener(
'click',
() => {
this.player.processNextBeat();
},
{ signal: this.abortController.signal }
);
this.resetButton.addEventListener(
'click',
() => {
this.player.reset();
},
{ signal: this.abortController.signal }
);
this.bpmInput.addEventListener(
'input',
() => {
const intVal = parseInt(this.bpmInput.value, 10);
if (!isNaN(intVal) && intVal > 0) {
this.player.bpm = intVal;
}
},
{ signal: this.abortController.signal }
);
this.notesPerBeatInput.addEventListener(
'input',
() => {
const val = parseInt(this.notesPerBeatInput.value, 10);
if (!isNaN(val) && val > 0) {
this.player.notesPerBeat = val;
}
this.updateColumns();
this.renderNotes();
},
{ signal: this.abortController.signal }
);
this.beatsPerBarInput.addEventListener(
'input',
() => {
this.updateColumns();
this.renderNotes();
},
{ signal: this.abortController.signal }
);
this.waveTypeSelect.addEventListener(
'change',
() => {
if (isValidWaveType(this.waveTypeSelect.value)) {
this.player.waveType = this.waveTypeSelect.value;
}
},
{ signal: this.abortController.signal }
);
this.player.addEventListener(
'waveTypeChange',
() => {
this.waveTypeSelect.value = this.player.waveType;
},
{ signal: this.abortController.signal }
);
}
private updateColumns() {
const notesPerBeat = parseInt(this.notesPerBeatInput.value, 10);
const beatsPerBar = parseInt(this.beatsPerBarInput.value, 10);
if (notesPerBeat > 0 && beatsPerBar > 0) {
this.notesContainer.style.setProperty(
'--columns',
`${notesPerBeat * beatsPerBar}`
);
}
}
setSong(song: string) {
this.songInput.value = song;
const newNotes = parseSong(song);
if (!arrayEqual(newNotes, this.player.directives)) {
this.player.directives = newNotes;
}
}
toggleAutoplay() {
if (this.player.isAutoplaying()) {
this.player.stopAutoplay();
} else {
this.player.beginAutoplay();
}
}
renderNotes() {
const noteCount = this.player.directives.length;
const eleCount = this.notesContainer.childElementCount;
let modifier: string | null = null;
let pre: string | null = null;
let lastElement: HTMLDivElement | null = null;
let directiveStart = -1;
let elementIndex = -1;
for (
let directiveIndex = 0;
directiveIndex < noteCount;
directiveIndex++
) {
const directive = this.player.directives[directiveIndex];
if (directive.type === 'voice') {
modifier = directive.voice;
continue;
}
if (directive.type === 'beginRepeat') {
pre = `${pre ?? ''}|:`;
continue;
}
if (directive.type === 'endRepeat') {
if (lastElement) {
lastElement.innerText += ':|';
}
continue;
}
if (directive.type === 'halt') {
if (lastElement) {
lastElement.innerText += '||';
}
continue;
}
elementIndex++;
let ele: HTMLDivElement | null = null;
if (elementIndex >= eleCount) {
ele = document.createElement('div');
ele.classList.add('note');
this.notesContainer.appendChild(ele);
} else {
ele = this.notesContainer.children[
elementIndex
] as HTMLDivElement;
}
const index = directiveStart;
ele.onclick = () => {
this.player.head = index;
this.player.clearRepeats();
this.player.processNextBeat();
};
lastElement = ele;
directiveStart = directiveIndex;
if (elementIndex > 0) {
ele.style.marginRight =
this.notesPerBeatInput.value !== '1' &&
(elementIndex + 1) %
parseInt(this.notesPerBeatInput.value) ===
0
? '1rem'
: '0';
ele.style.marginBottom =
(elementIndex + 1) %
(parseInt(this.notesPerBeatInput.value) *
parseInt(this.beatsPerBarInput.value) *
4) ===
0
? '2rem'
: '0';
}
ele.innerText = [
modifier,
[pre, directiveToString(directive)].filter((n) => n).join(' '),
]
.filter((n) => n)
.join('\n');
modifier = null;
pre = null;
ele.classList.toggle('active', directiveIndex === this.player.head);
}
while (elementIndex < eleCount - 1) {
this.notesContainer.removeChild(this.notesContainer.lastChild!);
elementIndex++;
}
}
}
const songInput = document.getElementById('song');
if (!songInput || !(songInput instanceof HTMLTextAreaElement)) {
throw new Error('Could not find song input');
}
const autoplayButton = document.getElementById('autoplay');
if (!autoplayButton || !(autoplayButton instanceof HTMLButtonElement)) {
throw new Error('Could not find autoplay button');
}
const playNextButton = document.getElementById('playNext');
if (!playNextButton || !(playNextButton instanceof HTMLButtonElement)) {
throw new Error('Could not find play next button');
}
const resetButton = document.getElementById('reset');
if (!resetButton || !(resetButton instanceof HTMLButtonElement)) {
throw new Error('Could not find reset button');
}
const bpmInput = document.getElementById('bpm');
if (!bpmInput || !(bpmInput instanceof HTMLInputElement)) {
throw new Error('Could not find bpm input');
}
const notesPerBeatInput = document.getElementById('notesPerBeat');
if (!notesPerBeatInput || !(notesPerBeatInput instanceof HTMLInputElement)) {
throw new Error('Could not find notes per beat input');
}
const beatsPerBarInput = document.getElementById('beatsPerBar');
if (!beatsPerBarInput || !(beatsPerBarInput instanceof HTMLInputElement)) {
throw new Error('Could not find beats per bar input');
}
const waveTypeSelect = document.getElementById('waveType');
if (!waveTypeSelect || !(waveTypeSelect instanceof HTMLSelectElement)) {
throw new Error('Could not find wave type select');
}
const notesContainer = document.getElementById('notes');
if (!notesContainer || !(notesContainer instanceof HTMLDivElement)) {
throw new Error('Could not find notes container');
}
const loadHelpContentButton = document.getElementById('loadHelpContent');
if (
!loadHelpContentButton ||
!(loadHelpContentButton instanceof HTMLButtonElement)
) {
throw new Error('Could not find load help content button');
}
const player = new Player();
const playerController = new PlayerController(
player,
songInput,
autoplayButton,
playNextButton,
resetButton,
bpmInput,
notesPerBeatInput,
beatsPerBarInput,
waveTypeSelect,
notesContainer,
loadHelpContentButton
);
const savedSong = localStorage.getItem(PlayerController.AUTOSAVE_NAME);
if (savedSong) {
playerController.setSong(savedSong);
}
function isValidWaveType(
val: string
): val is Exclude<OscillatorType, 'custom'> {
return ['sine', 'sawtooth', 'square', 'triangle'].includes(val);
}
function arrayEqual<T>(a: T[], b: T[]): boolean {
if (a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
function directiveToString(directive: Directive): string {
switch (directive.type) {
case 'rest':
return '_';
case 'voice':
return directive.voice;
case 'halt':
return '||';
case 'beginRepeat':
return '|:';
case 'endRepeat':
return ':|';
case 'chord':
return directive.notes.map(noteToString).join('-');
}
}
function noteToString(note: Note): string {
return `${note.key}${note.octave}${'~'.repeat(note.sustain - 1)}`;
}
function parseNote(note: string): Note | null {
if (note === '_') return null;
const match = noteRegex.exec(note);
if (!match) {
return null;
}
const { key, octave, sustain } = match.groups as Record<
'key' | 'octave' | 'sustain',
string
>;
if (!isValidKey(key)) {
return null;
}
const octaveInt = parseInt(octave || '4');
const sustainInt = sustain.length + 1;
return { key, octave: octaveInt, sustain: sustainInt };
}
function isValidKey(key: string): key is keyof typeof KEYS {
return key in KEYS;
}
function getFrequency(key: keyof typeof KEYS, octave: number) {
const step = KEYS[key];
const a4 = 440;
return a4 * Math.pow(2, octave - 4 + (step - 1) / 12);
}
function parseChord(chord: string) {
const parts = chord.split('-');
return parts.map(parseNote).filter((n): n is Note => !!n);
}
function parseWord(word: string) {
if (word === '_') {
return { type: 'rest' };
}
if (word === '||') {
return { type: 'halt' };
}
if (word === '|:') {
return { type: 'beginRepeat' };
}
if (word === ':|') {
return { type: 'endRepeat' };
}
if (isValidWaveType(word)) {
return { type: 'voice', voice: word };
}
const chord = parseChord(word);
if (chord.length > 0) {
return { type: 'chord', notes: chord };
}
return null;
}
function parseSong(song: string) {
const songNoComments = song
.split('\n')
.map((l) => l.replace(/\/\/.*$/, '').trim())
.filter((l) => l.length > 0)
.join('');
const words: string[] = [];
songNoComments.replace(
/(([A-G][#b]?(?:\d+)?(?:~*))(\-[A-G][#b]?(?:\d+)?(?:~*))*|_|sawtooth|square|sine|triangle|\|\||\|\:|\:\|)/g,
(match) => {
words.push(match);
return match;
}
);
return words.map(parseWord).filter((w): w is Directive => !!w);
}