-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnes.js
1322 lines (1123 loc) · 36 KB
/
nes.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
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
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
"use strict";
module.exports = {
tempo: 120,
octave: 4,
length: 4,
velocity: 100,
quantize: 75,
loopCount: 2
};
},{}],2:[function(require,module,exports){
"use strict";
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Syntax = require("./Syntax");
var DefaultParams = require("./DefaultParams");
var MMLParser = require("./MMLParser");
var ITERATOR = typeof Symbol !== "undefined" ? Symbol.iterator : "@@iterator";
var MMLIterator = function () {
function MMLIterator(source) {
_classCallCheck(this, MMLIterator);
this.source = source;
this._commands = new MMLParser(source).parse();
this._commandIndex = 0;
this._processedTime = 0;
this._iterator = null;
this._octave = DefaultParams.octave;
this._noteLength = [DefaultParams.length];
this._velocity = DefaultParams.velocity;
this._quantize = DefaultParams.quantize;
this._tempo = DefaultParams.tempo;
this._infiniteLoopIndex = -1;
this._loopStack = [];
this._done = false;
}
_createClass(MMLIterator, [{
key: "hasNext",
value: function hasNext() {
return this._commandIndex < this._commands.length;
}
}, {
key: "next",
value: function next() {
if (this._done) {
return { done: true, value: null };
}
if (this._iterator) {
var iterItem = this._iterator.next();
if (!iterItem.done) {
return iterItem;
}
}
var command = this._forward(true);
if (isNoteEvent(command)) {
this._iterator = this[command.type](command);
} else {
this._done = true;
return { done: false, value: { type: "end", time: this._processedTime } };
}
return this.next();
}
}, {
key: ITERATOR,
value: function value() {
return this;
}
}, {
key: "_forward",
value: function _forward(forward) {
while (this.hasNext() && !isNoteEvent(this._commands[this._commandIndex])) {
var command = this._commands[this._commandIndex++];
this[command.type](command);
}
if (forward && !this.hasNext() && this._infiniteLoopIndex !== -1) {
this._commandIndex = this._infiniteLoopIndex;
return this._forward(false);
}
return this._commands[this._commandIndex++] || {};
}
}, {
key: "_calcDuration",
value: function _calcDuration(noteLength) {
var _this = this;
if (noteLength[0] === null) {
noteLength = this._noteLength.concat(noteLength.slice(1));
}
var prev = null;
var dotted = 0;
noteLength = noteLength.map(function (elem) {
switch (elem) {
case null:
elem = prev;
break;
case 0:
elem = dotted *= 2;
break;
default:
prev = dotted = elem;
break;
}
var length = elem !== null ? elem : DefaultParams.length;
return 60 / _this._tempo * (4 / length);
});
return noteLength.reduce(function (a, b) {
return a + b;
}, 0);
}
}, {
key: "_calcNoteNumber",
value: function _calcNoteNumber(noteNumber) {
return noteNumber + this._octave * 12 + 12;
}
}, {
key: Syntax.Note,
value: function value(command) {
var _this2 = this;
var type = "note";
var time = this._processedTime;
var duration = this._calcDuration(command.noteLength);
var noteNumbers = command.noteNumbers.map(function (noteNumber) {
return _this2._calcNoteNumber(noteNumber);
});
var quantize = this._quantize;
var velocity = this._velocity;
this._processedTime = this._processedTime + duration;
return arrayToIterator(noteNumbers.map(function (noteNumber) {
return { type: type, time: time, duration: duration, noteNumber: noteNumber, velocity: velocity, quantize: quantize };
}));
}
}, {
key: Syntax.Rest,
value: function value(command) {
var duration = this._calcDuration(command.noteLength);
this._processedTime = this._processedTime + duration;
}
}, {
key: Syntax.Octave,
value: function value(command) {
this._octave = command.value !== null ? command.value : DefaultParams.octave;
}
}, {
key: Syntax.OctaveShift,
value: function value(command) {
var value = command.value !== null ? command.value : 1;
this._octave += value * command.direction;
}
}, {
key: Syntax.NoteLength,
value: function value(command) {
var noteLength = command.noteLength.map(function (value) {
return value !== null ? value : DefaultParams.length;
});
this._noteLength = noteLength;
}
}, {
key: Syntax.NoteVelocity,
value: function value(command) {
this._velocity = command.value !== null ? command.value : DefaultParams.velocity;
}
}, {
key: Syntax.NoteQuantize,
value: function value(command) {
this._quantize = command.value !== null ? command.value : DefaultParams.quantize;
}
}, {
key: Syntax.Tempo,
value: function value(command) {
this._tempo = command.value !== null ? command.value : DefaultParams.tempo;
}
}, {
key: Syntax.InfiniteLoop,
value: function value() {
this._infiniteLoopIndex = this._commandIndex;
}
}, {
key: Syntax.LoopBegin,
value: function value(command) {
var loopCount = command.value !== null ? command.value : DefaultParams.loopCount;
var loopTopIndex = this._commandIndex;
var loopOutIndex = -1;
this._loopStack.push({ loopCount: loopCount, loopTopIndex: loopTopIndex, loopOutIndex: loopOutIndex });
}
}, {
key: Syntax.LoopExit,
value: function value() {
var looper = this._loopStack[this._loopStack.length - 1];
var index = this._commandIndex;
if (looper.loopCount <= 1 && looper.loopOutIndex !== -1) {
index = looper.loopOutIndex;
}
this._commandIndex = index;
}
}, {
key: Syntax.LoopEnd,
value: function value() {
var looper = this._loopStack[this._loopStack.length - 1];
var index = this._commandIndex;
if (looper.loopOutIndex === -1) {
looper.loopOutIndex = this._commandIndex;
}
looper.loopCount -= 1;
if (0 < looper.loopCount) {
index = looper.loopTopIndex;
} else {
this._loopStack.pop();
}
this._commandIndex = index;
}
}]);
return MMLIterator;
}();
function arrayToIterator(array) {
var index = 0;
return {
next: function next() {
if (index < array.length) {
return { done: false, value: array[index++] };
}
return { done: true };
}
};
}
function isNoteEvent(command) {
return command.type === Syntax.Note || command.type === Syntax.Rest;
}
module.exports = MMLIterator;
},{"./DefaultParams":1,"./MMLParser":3,"./Syntax":5}],3:[function(require,module,exports){
"use strict";
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Syntax = require("./Syntax");
var Scanner = require("./Scanner");
var NOTE_INDEXES = { c: 0, d: 2, e: 4, f: 5, g: 7, a: 9, b: 11 };
var MMLParser = function () {
function MMLParser(source) {
_classCallCheck(this, MMLParser);
this.scanner = new Scanner(source);
}
_createClass(MMLParser, [{
key: "parse",
value: function parse() {
var _this = this;
var result = [];
this._readUntil(";", function () {
result = result.concat(_this.advance());
});
return result;
}
}, {
key: "advance",
value: function advance() {
switch (this.scanner.peek()) {
case "c":
case "d":
case "e":
case "f":
case "g":
case "a":
case "b":
return this.readNote();
case "[":
return this.readChord();
case "r":
return this.readRest();
case "o":
return this.readOctave();
case ">":
return this.readOctaveShift(+1);
case "<":
return this.readOctaveShift(-1);
case "l":
return this.readNoteLength();
case "q":
return this.readNoteQuantize();
case "v":
return this.readNoteVelocity();
case "t":
return this.readTempo();
case "$":
return this.readInfiniteLoop();
case "/":
return this.readLoop();
default:
// do nothing
}
this.scanner.throwUnexpectedToken();
}
}, {
key: "readNote",
value: function readNote() {
return {
type: Syntax.Note,
noteNumbers: [this._readNoteNumber(0)],
noteLength: this._readLength()
};
}
}, {
key: "readChord",
value: function readChord() {
var _this2 = this;
this.scanner.expect("[");
var noteList = [];
var offset = 0;
this._readUntil("]", function () {
switch (_this2.scanner.peek()) {
case "c":
case "d":
case "e":
case "f":
case "g":
case "a":
case "b":
noteList.push(_this2._readNoteNumber(offset));
break;
case ">":
_this2.scanner.next();
offset += 12;
break;
case "<":
_this2.scanner.next();
offset -= 12;
break;
default:
_this2.scanner.throwUnexpectedToken();
}
});
this.scanner.expect("]");
return {
type: Syntax.Note,
noteNumbers: noteList,
noteLength: this._readLength()
};
}
}, {
key: "readRest",
value: function readRest() {
this.scanner.expect("r");
return {
type: Syntax.Rest,
noteLength: this._readLength()
};
}
}, {
key: "readOctave",
value: function readOctave() {
this.scanner.expect("o");
return {
type: Syntax.Octave,
value: this._readArgument(/\d+/)
};
}
}, {
key: "readOctaveShift",
value: function readOctaveShift(direction) {
this.scanner.expect(/<|>/);
return {
type: Syntax.OctaveShift,
direction: direction | 0,
value: this._readArgument(/\d+/)
};
}
}, {
key: "readNoteLength",
value: function readNoteLength() {
this.scanner.expect("l");
return {
type: Syntax.NoteLength,
noteLength: this._readLength()
};
}
}, {
key: "readNoteQuantize",
value: function readNoteQuantize() {
this.scanner.expect("q");
return {
type: Syntax.NoteQuantize,
value: this._readArgument(/\d+/)
};
}
}, {
key: "readNoteVelocity",
value: function readNoteVelocity() {
this.scanner.expect("v");
return {
type: Syntax.NoteVelocity,
value: this._readArgument(/\d+/)
};
}
}, {
key: "readTempo",
value: function readTempo() {
this.scanner.expect("t");
return {
type: Syntax.Tempo,
value: this._readArgument(/\d+(\.\d+)?/)
};
}
}, {
key: "readInfiniteLoop",
value: function readInfiniteLoop() {
this.scanner.expect("$");
return {
type: Syntax.InfiniteLoop
};
}
}, {
key: "readLoop",
value: function readLoop() {
var _this3 = this;
this.scanner.expect("/");
this.scanner.expect(":");
var loopBegin = { type: Syntax.LoopBegin };
var loopEnd = { type: Syntax.LoopEnd };
var result = [];
result = result.concat(loopBegin);
this._readUntil(/[|:]/, function () {
result = result.concat(_this3.advance());
});
result = result.concat(this._readLoopExit());
this.scanner.expect(":");
this.scanner.expect("/");
loopBegin.value = this._readArgument(/\d+/) || null;
result = result.concat(loopEnd);
return result;
}
}, {
key: "_readUntil",
value: function _readUntil(matcher, callback) {
while (this.scanner.hasNext()) {
this.scanner.forward();
if (!this.scanner.hasNext() || this.scanner.match(matcher)) {
break;
}
callback();
}
}
}, {
key: "_readArgument",
value: function _readArgument(matcher) {
var num = this.scanner.scan(matcher);
return num !== null ? +num : null;
}
}, {
key: "_readNoteNumber",
value: function _readNoteNumber(offset) {
var noteIndex = NOTE_INDEXES[this.scanner.next()];
return noteIndex + this._readAccidental() + offset;
}
}, {
key: "_readAccidental",
value: function _readAccidental() {
if (this.scanner.match("+")) {
return +1 * this.scanner.scan(/\++/).length;
}
if (this.scanner.match("-")) {
return -1 * this.scanner.scan(/\-+/).length;
}
return 0;
}
}, {
key: "_readDot",
value: function _readDot() {
var len = (this.scanner.scan(/\.+/) || "").length;
var result = new Array(len);
for (var i = 0; i < len; i++) {
result[i] = 0;
}
return result;
}
}, {
key: "_readLength",
value: function _readLength() {
var result = [];
result = result.concat(this._readArgument(/\d+/));
result = result.concat(this._readDot());
var tie = this._readTie();
if (tie) {
result = result.concat(tie);
}
return result;
}
}, {
key: "_readTie",
value: function _readTie() {
this.scanner.forward();
if (this.scanner.match("^")) {
this.scanner.next();
return this._readLength();
}
return null;
}
}, {
key: "_readLoopExit",
value: function _readLoopExit() {
var _this4 = this;
var result = [];
if (this.scanner.match("|")) {
this.scanner.next();
var loopExit = { type: Syntax.LoopExit };
result = result.concat(loopExit);
this._readUntil(":", function () {
result = result.concat(_this4.advance());
});
}
return result;
}
}]);
return MMLParser;
}();
module.exports = MMLParser;
},{"./Scanner":4,"./Syntax":5}],4:[function(require,module,exports){
"use strict";
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Scanner = function () {
function Scanner(source) {
_classCallCheck(this, Scanner);
this.source = source;
this.index = 0;
}
_createClass(Scanner, [{
key: "hasNext",
value: function hasNext() {
return this.index < this.source.length;
}
}, {
key: "peek",
value: function peek() {
return this.source.charAt(this.index) || "";
}
}, {
key: "next",
value: function next() {
return this.source.charAt(this.index++) || "";
}
}, {
key: "forward",
value: function forward() {
while (this.hasNext() && this.match(/\s/)) {
this.index += 1;
}
}
}, {
key: "match",
value: function match(matcher) {
if (matcher instanceof RegExp) {
return matcher.test(this.peek());
}
return this.peek() === matcher;
}
}, {
key: "expect",
value: function expect(matcher) {
if (!this.match(matcher)) {
this.throwUnexpectedToken();
}
this.index += 1;
}
}, {
key: "scan",
value: function scan(matcher) {
var target = this.source.substr(this.index);
var result = null;
if (matcher instanceof RegExp) {
var matched = matcher.exec(target);
if (matched && matched.index === 0) {
result = matched[0];
}
} else if (target.substr(0, matcher.length) === matcher) {
result = matcher;
}
if (result) {
this.index += result.length;
}
return result;
}
}, {
key: "throwUnexpectedToken",
value: function throwUnexpectedToken() {
var identifier = this.peek() || "ILLEGAL";
throw new SyntaxError("Unexpected token: " + identifier);
}
}]);
return Scanner;
}();
module.exports = Scanner;
},{}],5:[function(require,module,exports){
"use strict";
module.exports = {
Note: "Note",
Rest: "Rest",
Octave: "Octave",
OctaveShift: "OctaveShift",
NoteLength: "NoteLength",
NoteVelocity: "NoteVelocity",
NoteQuantize: "NoteQuantize",
Tempo: "Tempo",
InfiniteLoop: "InfiniteLoop",
LoopBegin: "LoopBegin",
LoopExit: "LoopExit",
LoopEnd: "LoopEnd"
};
},{}],6:[function(require,module,exports){
"use strict";
module.exports = require("./MMLIterator");
},{"./MMLIterator":2}],7:[function(require,module,exports){
/**
* Module for adding effects to existing melodies
* @module NES.Effects
* @see NES
*/
module.exports = {
/**
* Takes a sequence of melody notes and converts them to a shorter, staccato representation
* @param {Array} melody The melody to shorten
* @param {Number} noteReduction The percentage (0 - 1) to reduce the note length by
* @return Array An updated melody, with shortened notes
*/
Staccato: function (melody, noteReduction) {
noteReduction = noteReduction || 0.5
var newMelody = []
for (var i = 0; i < melody.length; i++) {
var shortCycles = Math.round(melody[i].cycles * noteReduction)
newMelody.push({
frequency: melody[i].frequency,
cycles: shortCycles,
volume: melody[i].volume
})
newMelody.push({
frequency: melody[i + 1] ? melody[i + 1].frequency : melody[i].frequency,
cycles: melody[i].cycles - shortCycles,
volume: 0
})
}
return newMelody
},
/**
* Takes a chord of frequencies and converts them into an arpeggiated chords that arpegiates at 60Hz (60 notes per
* second, the NES limit)
* @param {Array} frequencies An array of floating-point frequencies
* @param {Number} cycles The number of cycles to run
* @param {Number} startVolume The starting volume (0 - 1)
* @param {Number} endVolume The ending volume (0 - 1), defaults to the starting volume
* @return {Array} An array of notes that arpeggiates given the passed parameters
*/
Arpeggio: function (frequencies, cycles, startVolume, endVolume) {
endVolume = endVolume === undefined ? startVolume : endVolume
var melody = []
for (var i = 0; i < cycles; i++) {
var volume = startVolume + (endVolume - startVolume) * i / cycles
var frequencyIndex = i % frequencies.length
melody.push({
frequency: frequencies[frequencyIndex],
volume: volume,
cycles: 1
})
}
return melody
},
/**
* Adds vibrato to a given melody. Typical might look like this: NES.Effects.Vibrato(myMelody, 5, 0.015)
* @param {Array} melody The melody to add vibrato to
* @param {Number} vibratoFrequency The frequency at which to oscillate the note
* @param {Number} vibratoPercentage The percentage to vibrate by.
* @return {Array} An updated, vibrato melody
*/
Vibrato: function (melody, vibratoFrequency, vibratoPercentage) {
var vibratoMelodyComponents = melody.map(function (note) {
var melody = []
for (var cycle = 0; cycle < note.cycles; cycle++) {
var t = cycle / 60
var offsetRatio = 1 + vibratoPercentage * Math.sin(t * 2 * Math.PI * vibratoFrequency)
melody.push({
volume: note.volume,
cycles: 1,
frequency: note.frequency * offsetRatio
})
}
return melody
})
// flatten
return Array.prototype.concat.apply([], vibratoMelodyComponents)
}
}
},{}],8:[function(require,module,exports){
/**
* @module NES.Events.Bus
*/
var bus = {
listeners: {},
/**
* Triggers an event
* @param {String} name The name of the event to trigger
* @param {Object} data The data to emit with the event
*/
trigger: function (name, data) {
if (this.listeners[name] === undefined) {
return
}
for (var i = 0; i < this.listeners[name].length; i++) {
this.listeners[name][i](data)
}
},
/**
* Registers an event listener
* @param {String} name The event to listen to
* @param {Function} callback The function to call when the event is emitted
*/
addEventListener: function (name, callback) {
if (this.listeners[name] === undefined) {
this.listeners[name] = []
}
this.listeners[name].push(callback)
},
/**
* Removes a registered event listener
* @param {String} name The event the listener is attached to
* @param {Function} callback The function to remove
*/
removeEventListener: function (name, callback) {
if (this.listeners[name] === undefined) {
return
}
var index = this.listeners[name].indexOf(callback)
if (index === -1) {
return index
}
this.listeners[name].splice(index, 1)
return index
}
}
var types = {
OSCILLATOR_CHANGE: 'OSCILLATOR_CHANGE',
SEQUENCER_TICK: 'SEQUENCER_TICK'
}
/**
* Utilities for emitting events
* @module NES.Events
*/
module.exports = {
/**
* An event bus that the sequencer uses to emit events
* @module NES.Events.Bus
*/
Bus: bus,
/**
* An enum of event types that get emitted
* @module NES.Events.Types
*/
Types: types
}
},{}],9:[function(require,module,exports){
var MMLIterator = require('mml-iterator')
var Effects = require('./effects')
var noteNumberToFrequency = function (noteNumber) {
// a440 is 69
var halftoneOffset = noteNumber - 69
return 440 * Math.pow(2, halftoneOffset / 12)
}
var cycles = function (duration) {
var alpha = 100000000
return Math.round(Math.round(duration * 60 * alpha) / alpha)
}
/**
* A module for working with MML
* @module NES.Mml
* @see NES
*/
module.exports = {
/**
* Converts an mml string to an array of notes for the sequencer
* @param {String} mmlString A string of mml to convert. Something like "t100 cde2fg^"
* @return {Array} An array of notes that can be passed to the sequencer's play method
*/
mmlToMelody: function (mmlString) {
var iterator = new MMLIterator(mmlString)
// each entry is a "chord grouping", potentially with one note per grouping
var chordGroupings = [[]]
var current = iterator.next()
var lastTime = current.value.time
// handle the starting rest as well
if (lastTime > 0) {
chordGroupings[chordGroupings.length - 1].push({
frequency: 440,
volume: 0,
cycles: cycles(lastTime)
})
chordGroupings.push([])
}
var lastNoteEnd = current.value.duration + lastTime
while (current.value.type !== 'end') {
// check if we need to add a rest. We'll need to add a rest if the current note ends before the next one starts
if (current.value.time > lastNoteEnd) {
var restLength = current.value.time - lastNoteEnd
chordGroupings.push([{
frequency: noteNumberToFrequency(current.value.noteNumber),
volume: 0,
cycles: cycles(restLength)
}])
chordGroupings.push([])
} else if (current.value.time !== lastTime) {
// if our current note doesn't occur at the same time as the last one, create a new chord grouping
chordGroupings.push([])
}
// push the current note onto the end of the current chord grouping
chordGroupings[chordGroupings.length - 1].push({
frequency: noteNumberToFrequency(current.value.noteNumber),
volume: current.value.velocity / 127,
cycles: cycles(current.value.duration)
})
lastTime = current.value.time
lastNoteEnd = current.value.duration + current.value.time
current = iterator.next()
}
var melody = []
chordGroupings.forEach(function (chord) {
if (chord.length === 1) {
return melody.push(chord[0])
}
var frequencies = chord.map(function (note) {
return note.frequency
})
melody = melody.concat(Effects.Arpeggio(frequencies, chord[0].cycles, chord[0].volume))
})
melody.push({ frequency: 440, volume: 0, cycles: 1 })
return melody
}
}
},{"./effects":7,"mml-iterator":6}],10:[function(require,module,exports){
/**
* A few helpful functions for music-based calculations
* @module NES.MusicTools
* @see NES
*/
module.exports = {
/**
* A set of tempos with subdivisions (down a 32nd note) that line up evenly on the NES's cycle speed
*/
tempos: {
Grave: 37.5,
Largo: 50,
Adagio: 75,
Andante: 90,
Moderato: 112.5,
Allegro: 150,
Presto: 225
},
/**
* Calculates the frequency for a given note in scientific pitch notation
* @param {String} note A string to convert (like "A5", "Db3" or "G#4")
* @return {Number} The frequency of the note
*/
frequency: function (note) {
var octave = Number(note[note.length - 1])
var pitch = note.substr(0, note.length - 1)
var pitchNames = [
['C', 'B#'],