-
Notifications
You must be signed in to change notification settings - Fork 0
/
midi.js
1783 lines (1652 loc) · 51.5 KB
/
midi.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
/*
----------------------------------------------------------
MIDI.audioDetect : 0.3.2 : 2015-03-26
----------------------------------------------------------
https://github.com/mudcube/MIDI.js
----------------------------------------------------------
Probably, Maybe, No... Absolutely!
Test to see what types of <audio> MIME types are playable by the browser.
----------------------------------------------------------
*/
if (typeof MIDI === 'undefined') var MIDI = {};
(function(root) { 'use strict';
var supports = {}; // object of supported file types
var pending = 0; // pending file types to process
var canPlayThrough = function (src) { // check whether format plays through
pending ++;
var body = document.body;
var audio = new Audio();
var mime = src.split(';')[0];
audio.id = 'audio';
audio.setAttribute('preload', 'auto');
audio.setAttribute('audiobuffer', true);
audio.addEventListener('error', function() {
body.removeChild(audio);
supports[mime] = false;
pending --;
}, false);
audio.addEventListener('canplaythrough', function() {
body.removeChild(audio);
supports[mime] = true;
pending --;
}, false);
audio.src = 'data:' + src;
body.appendChild(audio);
};
root.audioDetect = function(onsuccess) {
/// detect jazz-midi plugin
if (navigator.requestMIDIAccess) {
var isNative = Function.prototype.toString.call(navigator.requestMIDIAccess).indexOf('[native code]');
if (isNative) { // has native midiapi support
supports['webmidi'] = true;
} else { // check for jazz plugin midiapi support
for (var n = 0; navigator.plugins.length > n; n ++) {
var plugin = navigator.plugins[n];
if (plugin.name.indexOf('Jazz-Plugin') >= 0) {
supports['webmidi'] = true;
}
}
}
}
/// check whether <audio> tag is supported
if (typeof(Audio) === 'undefined') {
return onsuccess({});
} else {
supports['audiotag'] = true;
}
/// check for webaudio api support
if (window.AudioContext || window.webkitAudioContext) {
supports['webaudio'] = true;
}
/// check whether canPlayType is supported
var audio = new Audio();
if (typeof(audio.canPlayType) === 'undefined') {
return onsuccess(supports);
}
/// see what we can learn from the browser
var vorbis = audio.canPlayType('audio/ogg; codecs="vorbis"');
vorbis = (vorbis === 'probably' || vorbis === 'maybe');
var mpeg = audio.canPlayType('audio/mpeg');
mpeg = (mpeg === 'probably' || mpeg === 'maybe');
// maybe nothing is supported
if (!vorbis && !mpeg) {
onsuccess(supports);
return;
}
/// or maybe something is supported
if (vorbis) canPlayThrough('audio/ogg;base64,T2dnUwACAAAAAAAAAADqnjMlAAAAAOyyzPIBHgF2b3JiaXMAAAAAAUAfAABAHwAAQB8AAEAfAACZAU9nZ1MAAAAAAAAAAAAA6p4zJQEAAAANJGeqCj3//////////5ADdm9yYmlzLQAAAFhpcGguT3JnIGxpYlZvcmJpcyBJIDIwMTAxMTAxIChTY2hhdWZlbnVnZ2V0KQAAAAABBXZvcmJpcw9CQ1YBAAABAAxSFCElGVNKYwiVUlIpBR1jUFtHHWPUOUYhZBBTiEkZpXtPKpVYSsgRUlgpRR1TTFNJlVKWKUUdYxRTSCFT1jFloXMUS4ZJCSVsTa50FkvomWOWMUYdY85aSp1j1jFFHWNSUkmhcxg6ZiVkFDpGxehifDA6laJCKL7H3lLpLYWKW4q91xpT6y2EGEtpwQhhc+211dxKasUYY4wxxsXiUyiC0JBVAAABAABABAFCQ1YBAAoAAMJQDEVRgNCQVQBABgCAABRFcRTHcRxHkiTLAkJDVgEAQAAAAgAAKI7hKJIjSZJkWZZlWZameZaouaov+64u667t6roOhIasBACAAAAYRqF1TCqDEEPKQ4QUY9AzoxBDDEzGHGNONKQMMogzxZAyiFssLqgQBKEhKwKAKAAAwBjEGGIMOeekZFIi55iUTkoDnaPUUcoolRRLjBmlEluJMYLOUeooZZRCjKXFjFKJscRUAABAgAMAQICFUGjIigAgCgCAMAYphZRCjCnmFHOIMeUcgwwxxiBkzinoGJNOSuWck85JiRhjzjEHlXNOSuekctBJyaQTAAAQ4AAAEGAhFBqyIgCIEwAwSJKmWZomipamiaJniqrqiaKqWp5nmp5pqqpnmqpqqqrrmqrqypbnmaZnmqrqmaaqiqbquqaquq6nqrZsuqoum65q267s+rZru77uqapsm6or66bqyrrqyrbuurbtS56nqqKquq5nqq6ruq5uq65r25pqyq6purJtuq4tu7Js664s67pmqq5suqotm64s667s2rYqy7ovuq5uq7Ks+6os+75s67ru2rrwi65r66os674qy74x27bwy7ouHJMnqqqnqq7rmarrqq5r26rr2rqmmq5suq4tm6or26os67Yry7aumaosm64r26bryrIqy77vyrJui67r66Ys67oqy8Lu6roxzLat+6Lr6roqy7qvyrKuu7ru+7JuC7umqrpuyrKvm7Ks+7auC8us27oxuq7vq7It/KosC7+u+8Iy6z5jdF1fV21ZGFbZ9n3d95Vj1nVhWW1b+V1bZ7y+bgy7bvzKrQvLstq2scy6rSyvrxvDLux8W/iVmqratum6um7Ksq/Lui60dd1XRtf1fdW2fV+VZd+3hV9pG8OwjK6r+6os68Jry8ov67qw7MIvLKttK7+r68ow27qw3L6wLL/uC8uq277v6rrStXVluX2fsSu38QsAABhwAAAIMKEMFBqyIgCIEwBAEHIOKQahYgpCCKGkEEIqFWNSMuakZM5JKaWUFEpJrWJMSuaclMwxKaGUlkopqYRSWiqlxBRKaS2l1mJKqcVQSmulpNZKSa2llGJMrcUYMSYlc05K5pyUklJrJZXWMucoZQ5K6iCklEoqraTUYuacpA46Kx2E1EoqMZWUYgupxFZKaq2kFGMrMdXUWo4hpRhLSrGVlFptMdXWWqs1YkxK5pyUzDkqJaXWSiqtZc5J6iC01DkoqaTUYiopxco5SR2ElDLIqJSUWiupxBJSia20FGMpqcXUYq4pxRZDSS2WlFosqcTWYoy1tVRTJ6XFklKMJZUYW6y5ttZqDKXEVkqLsaSUW2sx1xZjjqGkFksrsZWUWmy15dhayzW1VGNKrdYWY40x5ZRrrT2n1mJNMdXaWqy51ZZbzLXnTkprpZQWS0oxttZijTHmHEppraQUWykpxtZara3FXEMpsZXSWiypxNhirLXFVmNqrcYWW62ltVprrb3GVlsurdXcYqw9tZRrrLXmWFNtBQAADDgAAASYUAYKDVkJAEQBAADGMMYYhEYpx5yT0ijlnHNSKucghJBS5hyEEFLKnINQSkuZcxBKSSmUklJqrYVSUmqttQIAAAocAAACbNCUWByg0JCVAEAqAIDBcTRNFFXVdX1fsSxRVFXXlW3jVyxNFFVVdm1b+DVRVFXXtW3bFn5NFFVVdmXZtoWiqrqybduybgvDqKqua9uybeuorqvbuq3bui9UXVmWbVu3dR3XtnXd9nVd+Bmzbeu2buu+8CMMR9/4IeTj+3RCCAAAT3AAACqwYXWEk6KxwEJDVgIAGQAAgDFKGYUYM0gxphhjTDHGmAAAgAEHAIAAE8pAoSErAoAoAADAOeecc84555xzzjnnnHPOOeecc44xxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMcYYY0wAwE6EA8BOhIVQaMhKACAcAABACCEpKaWUUkoRU85BSSmllFKqFIOMSkoppZRSpBR1lFJKKaWUIqWgpJJSSimllElJKaWUUkoppYw6SimllFJKKaWUUkoppZRSSimllFJKKaWUUkoppZRSSimllFJKKaWUUkoppZRSSimllFJKKaWUUkoppZRSSimllFJKKaVUSimllFJKKaWUUkoppRQAYPLgAACVYOMMK0lnhaPBhYasBAByAwAAhRiDEEJpraRUUkolVc5BKCWUlEpKKZWUUqqYgxBKKqmlklJKKbXSQSihlFBKKSWUUkooJYQQSgmhlFRCK6mEUkoHoYQSQimhhFRKKSWUzkEoIYUOQkmllNRCSB10VFIpIZVSSiklpZQ6CKGUklJLLZVSWkqpdBJSKamV1FJqqbWSUgmhpFZKSSWl0lpJJbUSSkklpZRSSymFVFJJJYSSUioltZZaSqm11lJIqZWUUkqppdRSSiWlkEpKqZSSUmollZRSaiGVlEpJKaTUSimlpFRCSamlUlpKLbWUSkmptFRSSaWUlEpJKaVSSksppRJKSqmllFpJKYWSUkoplZJSSyW1VEoKJaWUUkmptJRSSymVklIBAEAHDgAAAUZUWoidZlx5BI4oZJiAAgAAQABAgAkgMEBQMApBgDACAQAAAADAAAAfAABHARAR0ZzBAUKCwgJDg8MDAAAAAAAAAAAAAACAT2dnUwAEAAAAAAAAAADqnjMlAgAAADzQPmcBAQA=');
if (mpeg) canPlayThrough('audio/mpeg;base64,/+MYxAAAAANIAUAAAASEEB/jwOFM/0MM/90b/+RhST//w4NFwOjf///PZu////9lns5GFDv//l9GlUIEEIAAAgIg8Ir/JGq3/+MYxDsLIj5QMYcoAP0dv9HIjUcH//yYSg+CIbkGP//8w0bLVjUP///3Z0x5QCAv/yLjwtGKTEFNRTMuOTeqqqqqqqqqqqqq/+MYxEkNmdJkUYc4AKqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq');
/// lets find out!
var time = (new Date()).getTime();
var interval = window.setInterval(function() {
var now = (new Date()).getTime();
var maxExecution = now - time > 5000;
if (!pending || maxExecution) {
window.clearInterval(interval);
onsuccess(supports);
}
}, 1);
};
})(MIDI);
/*
----------------------------------------------------------
GeneralMIDI
----------------------------------------------------------
*/
(function(root) { 'use strict';
root.GM = (function(arr) {
var clean = function(name) {
return name.replace(/[^a-z0-9 ]/gi, '').replace(/[ ]/g, '_').toLowerCase();
};
var res = {
byName: { },
byId: { },
byCategory: { }
};
for (var key in arr) {
var list = arr[key];
for (var n = 0, length = list.length; n < length; n++) {
var instrument = list[n];
if (!instrument) continue;
var num = parseInt(instrument.substr(0, instrument.indexOf(' ')), 10);
instrument = instrument.replace(num + ' ', '');
res.byId[--num] =
res.byName[clean(instrument)] =
res.byCategory[clean(key)] = {
id: clean(instrument),
instrument: instrument,
number: num,
category: key
};
}
}
return res;
})({
'Piano': ['1 Acoustic Grand Piano', '2 Bright Acoustic Piano', '3 Electric Grand Piano', '4 Honky-tonk Piano', '5 Electric Piano 1', '6 Electric Piano 2', '7 Harpsichord', '8 Clavinet'],
'Chromatic Percussion': ['9 Celesta', '10 Glockenspiel', '11 Music Box', '12 Vibraphone', '13 Marimba', '14 Xylophone', '15 Tubular Bells', '16 Dulcimer'],
'Organ': ['17 Drawbar Organ', '18 Percussive Organ', '19 Rock Organ', '20 Church Organ', '21 Reed Organ', '22 Accordion', '23 Harmonica', '24 Tango Accordion'],
'Guitar': ['25 Acoustic Guitar (nylon)', '26 Acoustic Guitar (steel)', '27 Electric Guitar (jazz)', '28 Electric Guitar (clean)', '29 Electric Guitar (muted)', '30 Overdriven Guitar', '31 Distortion Guitar', '32 Guitar Harmonics'],
'Bass': ['33 Acoustic Bass', '34 Electric Bass (finger)', '35 Electric Bass (pick)', '36 Fretless Bass', '37 Slap Bass 1', '38 Slap Bass 2', '39 Synth Bass 1', '40 Synth Bass 2'],
'Strings': ['41 Violin', '42 Viola', '43 Cello', '44 Contrabass', '45 Tremolo Strings', '46 Pizzicato Strings', '47 Orchestral Harp', '48 Timpani'],
'Ensemble': ['49 String Ensemble 1', '50 String Ensemble 2', '51 Synth Strings 1', '52 Synth Strings 2', '53 Choir Aahs', '54 Voice Oohs', '55 Synth Choir', '56 Orchestra Hit'],
'Brass': ['57 Trumpet', '58 Trombone', '59 Tuba', '60 Muted Trumpet', '61 French Horn', '62 Brass Section', '63 Synth Brass 1', '64 Synth Brass 2'],
'Reed': ['65 Soprano Sax', '66 Alto Sax', '67 Tenor Sax', '68 Baritone Sax', '69 Oboe', '70 English Horn', '71 Bassoon', '72 Clarinet'],
'Pipe': ['73 Piccolo', '74 Flute', '75 Recorder', '76 Pan Flute', '77 Blown Bottle', '78 Shakuhachi', '79 Whistle', '80 Ocarina'],
'Synth Lead': ['81 Lead 1 (square)', '82 Lead 2 (sawtooth)', '83 Lead 3 (calliope)', '84 Lead 4 (chiff)', '85 Lead 5 (charang)', '86 Lead 6 (voice)', '87 Lead 7 (fifths)', '88 Lead 8 (bass + lead)'],
'Synth Pad': ['89 Pad 1 (new age)', '90 Pad 2 (warm)', '91 Pad 3 (polysynth)', '92 Pad 4 (choir)', '93 Pad 5 (bowed)', '94 Pad 6 (metallic)', '95 Pad 7 (halo)', '96 Pad 8 (sweep)'],
'Synth Effects': ['97 FX 1 (rain)', '98 FX 2 (soundtrack)', '99 FX 3 (crystal)', '100 FX 4 (atmosphere)', '101 FX 5 (brightness)', '102 FX 6 (goblins)', '103 FX 7 (echoes)', '104 FX 8 (sci-fi)'],
'Ethnic': ['105 Sitar', '106 Banjo', '107 Shamisen', '108 Koto', '109 Kalimba', '110 Bagpipe', '111 Fiddle', '112 Shanai'],
'Percussive': ['113 Tinkle Bell', '114 Agogo', '115 Steel Drums', '116 Woodblock', '117 Taiko Drum', '118 Melodic Tom', '119 Synth Drum'],
'Sound effects': ['120 Reverse Cymbal', '121 Guitar Fret Noise', '122 Breath Noise', '123 Seashore', '124 Bird Tweet', '125 Telephone Ring', '126 Helicopter', '127 Applause', '128 Gunshot']
});
/* get/setInstrument
--------------------------------------------------- */
root.getInstrument = function(channelId) {
var channel = root.channels[channelId];
return channel && channel.instrument;
};
root.setInstrument = function(channelId, program, delay) {
var channel = root.channels[channelId];
if (delay) {
return setTimeout(function() {
channel.instrument = program;
}, delay);
} else {
channel.instrument = program;
}
};
/* get/setMono
--------------------------------------------------- */
root.getMono = function(channelId) {
var channel = root.channels[channelId];
return channel && channel.mono;
};
root.setMono = function(channelId, truthy, delay) {
var channel = root.channels[channelId];
if (delay) {
return setTimeout(function() {
channel.mono = truthy;
}, delay);
} else {
channel.mono = truthy;
}
};
/* get/setOmni
--------------------------------------------------- */
root.getOmni = function(channelId) {
var channel = root.channels[channelId];
return channel && channel.omni;
};
root.setOmni = function(channelId, truthy) {
var channel = root.channels[channelId];
if (delay) {
return setTimeout(function() {
channel.omni = truthy;
}, delay);
} else {
channel.omni = truthy;
}
};
/* get/setSolo
--------------------------------------------------- */
root.getSolo = function(channelId) {
var channel = root.channels[channelId];
return channel && channel.solo;
};
root.setSolo = function(channelId, truthy) {
var channel = root.channels[channelId];
if (delay) {
return setTimeout(function() {
channel.solo = truthy;
}, delay);
} else {
channel.solo = truthy;
}
};
/* channels
--------------------------------------------------- */
root.channels = (function() { // 0 - 15 channels
var channels = {};
for (var i = 0; i < 16; i++) {
channels[i] = { // default values
instrument: i,
pitchBend: 0,
mute: false,
mono: false,
omni: false,
solo: false
};
}
return channels;
})();
/* note conversions
--------------------------------------------------- */
root.keyToNote = {}; // C8 == 108
root.noteToKey = {}; // 108 == C8
(function() {
var A0 = 0x15; // first note
var C8 = 0x6C; // last note
var number2key = ['C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B'];
for (var n = A0; n <= C8; n++) {
var octave = (n - 12) / 12 >> 0;
var name = number2key[n % 12] + octave;
root.keyToNote[name] = n;
root.noteToKey[n] = name;
}
})();
})(MIDI);
/*
----------------------------------------------------------
MIDI.Plugin : 0.3.4 : 2015-03-26
----------------------------------------------------------
https://github.com/mudcube/MIDI.js
----------------------------------------------------------
Inspired by javax.sound.midi (albeit a super simple version):
http://docs.oracle.com/javase/6/docs/api/javax/sound/midi/package-summary.html
----------------------------------------------------------
Technologies
----------------------------------------------------------
Web MIDI API - no native support yet (jazzplugin)
Web Audio API - firefox 25+, chrome 10+, safari 6+, opera 15+
HTML5 Audio Tag - ie 9+, firefox 3.5+, chrome 4+, safari 4+, opera 9.5+, ios 4+, android 2.3+
----------------------------------------------------------
*/
if (typeof MIDI === 'undefined') MIDI = {};
MIDI.Soundfont = MIDI.Soundfont || {};
MIDI.Player = MIDI.Player || {};
(function(root) { 'use strict';
root.DEBUG = true;
root.USE_XHR = true;
root.soundfontUrl = './soundfont/';
/*
MIDI.loadPlugin({
onsuccess: function() { },
onprogress: function(state, percent) { },
targetFormat: 'mp3', // optionally can force to use MP3 (for instance on mobile networks)
instrument: 'acoustic_grand_piano', // or 1 (default)
instruments: [ 'acoustic_grand_piano', 'acoustic_guitar_nylon' ] // or multiple instruments
});
*/
root.loadPlugin = function(opts) {
if (typeof opts === 'function') {
opts = {onsuccess: opts};
}
root.soundfontUrl = opts.soundfontUrl || root.soundfontUrl;
/// Detect the best type of audio to use
root.audioDetect(function(supports) {
var hash = window.location.hash;
var api = '';
/// use the most appropriate plugin if not specified
if (supports[opts.api]) {
api = opts.api;
} else if (supports[hash.substr(1)]) {
api = hash.substr(1);
} else if (supports.webmidi) {
api = 'webmidi';
} else if (window.AudioContext) { // Chrome
api = 'webaudio';
} else if (window.Audio) { // Firefox
api = 'audiotag';
}
if (connect[api]) {
/// use audio/ogg when supported
if (opts.targetFormat) {
var audioFormat = opts.targetFormat;
} else { // use best quality
var audioFormat = supports['audio/ogg'] ? 'ogg' : 'mp3';
}
/// load the specified plugin
root.__api = api;
root.__audioFormat = audioFormat;
root.supports = supports;
root.loadResource(opts);
}
});
};
/*
root.loadResource({
onsuccess: function() { },
onprogress: function(state, percent) { },
instrument: 'banjo'
})
*/
root.loadResource = function(opts) {
var instruments = opts.instruments || opts.instrument || 'acoustic_grand_piano';
///
if (typeof instruments !== 'object') {
if (instruments || instruments === 0) {
instruments = [instruments];
} else {
instruments = [];
}
}
/// convert numeric ids into strings
for (var i = 0; i < instruments.length; i ++) {
var instrument = instruments[i];
if (instrument === +instrument) { // is numeric
if (root.GM.byId[instrument]) {
instruments[i] = root.GM.byId[instrument].id;
}
}
}
///
opts.format = root.__audioFormat;
opts.instruments = instruments;
///
connect[root.__api](opts);
};
var connect = {
webmidi: function(opts) {
// cant wait for this to be standardized!
root.WebMIDI.connect(opts);
},
audiotag: function(opts) {
// works ok, kinda like a drunken tuna fish, across the board
// http://caniuse.com/audio
requestQueue(opts, 'AudioTag');
},
webaudio: function(opts) {
// works awesome! safari, chrome and firefox support
// http://caniuse.com/web-audio
requestQueue(opts, 'WebAudio');
}
};
var requestQueue = function(opts, context) {
var audioFormat = opts.format;
var instruments = opts.instruments;
var onprogress = opts.onprogress;
var onerror = opts.onerror;
///
var length = instruments.length;
var pending = length;
var waitForEnd = function() {
if (!--pending) {
onprogress && onprogress('load', 1.0);
root[context].connect(opts);
}
};
///
for (var i = 0; i < length; i ++) {
var instrumentId = instruments[i];
if (MIDI.Soundfont[instrumentId]) { // already loaded
waitForEnd();
} else { // needs to be requested
sendRequest(instruments[i], audioFormat, function(evt, progress) {
var fileProgress = progress / length;
var queueProgress = (length - pending) / length;
onprogress && onprogress('load', fileProgress + queueProgress, instrumentId);
}, function() {
waitForEnd();
}, onerror);
}
};
};
var sendRequest = function(instrumentId, audioFormat, onprogress, onsuccess, onerror) {
var soundfontPath = root.soundfontUrl + instrumentId + '-' + audioFormat + '.js';
if (root.USE_XHR) {
root.util.request({
url: soundfontPath,
format: 'text',
onerror: onerror,
onprogress: onprogress,
onsuccess: function(event, responseText) {
var script = document.createElement('script');
script.language = 'javascript';
script.type = 'text/javascript';
script.text = responseText;
document.body.appendChild(script);
///
onsuccess();
}
});
} else {
dom.loadScript.add({
url: soundfontPath,
verify: 'MIDI.Soundfont["' + instrumentId + '"]',
onerror: onerror,
onsuccess: function() {
onsuccess();
}
});
}
};
root.setDefaultPlugin = function(midi) {
for (var key in midi) {
root[key] = midi[key];
}
};
})(MIDI);
/*
----------------------------------------------------------
MIDI.Player : 0.3.1 : 2015-03-26
----------------------------------------------------------
https://github.com/mudcube/MIDI.js
----------------------------------------------------------
*/
if (typeof MIDI === 'undefined') MIDI = {};
if (typeof MIDI.Player === 'undefined') MIDI.Player = {};
(function() { 'use strict';
var midi = MIDI.Player;
midi.currentTime = 0;
midi.endTime = 0;
midi.restart = 0;
midi.playing = false;
midi.timeWarp = 1;
midi.startDelay = 0;
midi.BPM = 120;
midi.start =
midi.resume = function(onsuccess) {
if (midi.currentTime < -1) {
midi.currentTime = -1;
}
startAudio(midi.currentTime, null, onsuccess);
};
midi.pause = function() {
var tmp = midi.restart;
stopAudio();
midi.restart = tmp;
};
midi.stop = function() {
stopAudio();
midi.restart = 0;
midi.currentTime = 0;
};
midi.addListener = function(onsuccess) {
onMidiEvent = onsuccess;
};
midi.removeListener = function() {
onMidiEvent = undefined;
};
midi.clearAnimation = function() {
if (midi.animationFrameId) {
cancelAnimationFrame(midi.animationFrameId);
}
};
midi.setAnimation = function(callback) {
var currentTime = 0;
var tOurTime = 0;
var tTheirTime = 0;
//
midi.clearAnimation();
///
var frame = function() {
midi.animationFrameId = requestAnimationFrame(frame);
///
if (midi.endTime === 0) {
return;
}
if (midi.playing) {
currentTime = (tTheirTime === midi.currentTime) ? tOurTime - Date.now() : 0;
if (midi.currentTime === 0) {
currentTime = 0;
} else {
currentTime = midi.currentTime - currentTime;
}
if (tTheirTime !== midi.currentTime) {
tOurTime = Date.now();
tTheirTime = midi.currentTime;
}
} else { // paused
currentTime = midi.currentTime;
}
///
var endTime = midi.endTime;
var percent = currentTime / endTime;
var total = currentTime / 1000;
var minutes = total / 60;
var seconds = total - (minutes * 60);
var t1 = minutes * 60 + seconds;
var t2 = (endTime / 1000);
///
if (t2 - t1 < -1.0) {
return;
} else {
callback({
now: t1,
end: t2,
events: noteRegistrar
});
}
};
///
requestAnimationFrame(frame);
};
// helpers
midi.loadMidiFile = function(onsuccess, onprogress, onerror) {
try {
midi.replayer = new Replayer(MidiFile(midi.currentData), midi.timeWarp, null, midi.BPM);
midi.data = midi.replayer.getData();
midi.endTime = getLength();
///
MIDI.loadPlugin({
// instruments: midi.getFileInstruments(),
onsuccess: onsuccess,
onprogress: onprogress,
onerror: onerror
});
} catch(event) {
onerror && onerror(event);
}
};
midi.loadFile = function(file, onsuccess, onprogress, onerror) {
midi.stop();
if (file.indexOf('base64,') !== -1) {
var data = window.atob(file.split(',')[1]);
midi.currentData = data;
midi.loadMidiFile(onsuccess, onprogress, onerror);
} else {
var fetch = new XMLHttpRequest();
fetch.open('GET', file);
fetch.overrideMimeType('text/plain; charset=x-user-defined');
fetch.onreadystatechange = function() {
if (this.readyState === 4) {
if (this.status === 200) {
var t = this.responseText || '';
var ff = [];
var mx = t.length;
var scc = String.fromCharCode;
for (var z = 0; z < mx; z++) {
ff[z] = scc(t.charCodeAt(z) & 255);
}
///
var data = ff.join('');
midi.currentData = data;
midi.loadMidiFile(onsuccess, onprogress, onerror);
} else {
onerror && onerror('Unable to load MIDI file');
}
}
};
fetch.send();
}
};
midi.getFileInstruments = function() {
var instruments = {};
var programs = {};
for (var n = 0; n < midi.data.length; n ++) {
var event = midi.data[n][0].event;
if (event.type !== 'channel') {
continue;
}
var channel = event.channel;
switch(event.subtype) {
case 'controller':
// console.log(event.channel, MIDI.defineControl[event.controllerType], event.value);
break;
case 'programChange':
programs[channel] = event.programNumber;
break;
case 'noteOn':
var program = programs[channel];
var gm = MIDI.GM.byId[isFinite(program) ? program : channel];
instruments[gm.id] = true;
break;
}
}
var ret = [];
for (var key in instruments) {
ret.push(key);
}
return ret;
};
// Playing the audio
var eventQueue = []; // hold events to be triggered
var queuedTime; //
var startTime = 0; // to measure time elapse
var noteRegistrar = {}; // get event for requested note
var onMidiEvent = undefined; // listener
var scheduleTracking = function(channel, note, currentTime, offset, message, velocity, time) {
return setTimeout(function() {
var data = {
channel: channel,
note: note,
now: currentTime,
end: midi.endTime,
message: message,
velocity: velocity
};
//
if (message === 128) {
delete noteRegistrar[note];
} else {
noteRegistrar[note] = data;
}
if (onMidiEvent) {
onMidiEvent(data);
}
midi.currentTime = currentTime;
///
eventQueue.shift();
///
if (eventQueue.length < 1000) {
startAudio(queuedTime, true);
} else if (midi.currentTime === queuedTime && queuedTime < midi.endTime) { // grab next sequence
startAudio(queuedTime, true);
}
}, currentTime - offset);
};
var getContext = function() {
if (MIDI.api === 'webaudio') {
return MIDI.WebAudio.getContext();
} else {
midi.ctx = {currentTime: 0};
}
return midi.ctx;
};
var getLength = function() {
var data = midi.data;
var length = data.length;
var totalTime = 0.5;
for (var n = 0; n < length; n++) {
totalTime += data[n][1];
}
return totalTime;
};
var __now;
var getNow = function() {
if (window.performance && window.performance.now) {
return window.performance.now();
} else {
return Date.now();
}
};
var startAudio = function(currentTime, fromCache, onsuccess) {
if (!midi.replayer) {
return;
}
if (!fromCache) {
if (typeof currentTime === 'undefined') {
currentTime = midi.restart;
}
///
midi.playing && stopAudio();
midi.playing = true;
midi.data = midi.replayer.getData();
midi.endTime = getLength();
}
///
var note;
var offset = 0;
var messages = 0;
var data = midi.data;
var ctx = getContext();
var length = data.length;
//
queuedTime = 0.5;
///
var interval = eventQueue[0] && eventQueue[0].interval || 0;
var foffset = currentTime - midi.currentTime;
///
if (MIDI.api !== 'webaudio') { // set currentTime on ctx
var now = getNow();
__now = __now || now;
ctx.currentTime = (now - __now) / 1000;
}
///
startTime = ctx.currentTime;
///
for (var n = 0; n < length && messages < 100; n++) {
var obj = data[n];
if ((queuedTime += obj[1]) <= currentTime) {
offset = queuedTime;
continue;
}
///
currentTime = queuedTime - offset;
///
var event = obj[0].event;
if (event.type !== 'channel') {
continue;
}
///
var channelId = event.channel;
var channel = MIDI.channels[channelId];
var delay = ctx.currentTime + ((currentTime + foffset + midi.startDelay) / 1000);
var queueTime = queuedTime - offset + midi.startDelay;
switch (event.subtype) {
case 'controller':
MIDI.setController(channelId, event.controllerType, event.value, delay);
break;
case 'programChange':
MIDI.programChange(channelId, event.programNumber, delay);
break;
case 'pitchBend':
MIDI.pitchBend(channelId, event.value, delay);
break;
case 'noteOn':
if (channel.mute) break;
note = event.noteNumber - (midi.MIDIOffset || 0);
eventQueue.push({
event: event,
time: queueTime,
source: MIDI.noteOn(channelId, event.noteNumber, event.velocity, delay),
interval: scheduleTracking(channelId, note, queuedTime + midi.startDelay, offset - foffset, 144, event.velocity)
});
messages++;
break;
case 'noteOff':
if (channel.mute) break;
note = event.noteNumber - (midi.MIDIOffset || 0);
eventQueue.push({
event: event,
time: queueTime,
source: MIDI.noteOff(channelId, event.noteNumber, delay),
interval: scheduleTracking(channelId, note, queuedTime, offset - foffset, 128, 0)
});
break;
default:
break;
}
}
///
onsuccess && onsuccess(eventQueue);
};
var stopAudio = function() {
var ctx = getContext();
midi.playing = false;
midi.restart += (ctx.currentTime - startTime) * 1000;
// stop the audio, and intervals
while (eventQueue.length) {
var o = eventQueue.pop();
window.clearInterval(o.interval);
if (!o.source) continue; // is not webaudio
if (typeof(o.source) === 'number') {
window.clearTimeout(o.source);
} else { // webaudio
o.source.disconnect(0);
}
}
// run callback to cancel any notes still playing
for (var key in noteRegistrar) {
var o = noteRegistrar[key]
if (noteRegistrar[key].message === 144 && onMidiEvent) {
onMidiEvent({
channel: o.channel,
note: o.note,
now: o.now,
end: o.end,
message: 128,
velocity: o.velocity
});
}
}
// reset noteRegistrar
noteRegistrar = {};
};
})();
/*
----------------------------------------------------------------------
AudioTag <audio> - OGG or MPEG Soundbank
----------------------------------------------------------------------
http://dev.w3.org/html5/spec/Overview.html#the-audio-element
----------------------------------------------------------------------
*/
(function(root) { 'use strict';
window.Audio && (function() {
var midi = root.AudioTag = { api: 'audiotag' };
var noteToKey = {};
var volume = 127; // floating point
var buffer_nid = -1; // current channel
var audioBuffers = []; // the audio channels
var notesOn = []; // instrumentId + noteId that is currently playing in each 'channel', for routing noteOff/chordOff calls
var notes = {}; // the piano keys
for (var nid = 0; nid < 12; nid ++) {
audioBuffers[nid] = new Audio();
}
var playChannel = function(channel, note) {
if (!root.channels[channel]) return;
var instrument = root.channels[channel].instrument;
var instrumentId = root.GM.byId[instrument].id;
var note = notes[note];
if (note) {
var instrumentNoteId = instrumentId + '' + note.id;
var nid = (buffer_nid + 1) % audioBuffers.length;
var audio = audioBuffers[nid];
notesOn[ nid ] = instrumentNoteId;
if (!root.Soundfont[instrumentId]) {
if (root.DEBUG) {
console.log('404', instrumentId);
}
return;
}
audio.src = root.Soundfont[instrumentId][note.id];
audio.volume = volume / 127;
audio.play();
buffer_nid = nid;
}
};
var stopChannel = function(channel, note) {
if (!root.channels[channel]) return;
var instrument = root.channels[channel].instrument;
var instrumentId = root.GM.byId[instrument].id;
var note = notes[note];
if (note) {
var instrumentNoteId = instrumentId + '' + note.id;
for (var i = 0, len = audioBuffers.length; i < len; i++) {
var nid = (i + buffer_nid + 1) % len;
var cId = notesOn[nid];
if (cId && cId == instrumentNoteId) {
audioBuffers[nid].pause();
notesOn[nid] = null;
return;
}
}
}
};
midi.audioBuffers = audioBuffers;
midi.send = function(data, delay) { };
midi.setController = function(channel, type, value, delay) { };
midi.setVolume = function(channel, n) {
volume = n; //- should be channel specific volume
};
midi.programChange = function(channel, program) {
root.channels[channel].instrument = program;
};
midi.pitchBend = function(channel, program, delay) { };
midi.noteOn = function(channel, note, velocity, delay) {
var id = noteToKey[note];
if (!notes[id]) return;
if (delay) {
return setTimeout(function() {
playChannel(channel, id);
}, delay * 1000);
} else {
playChannel(channel, id);
}
};
midi.noteOff = function(channel, note, delay) {
// var id = noteToKey[note];
// if (!notes[id]) return;
// if (delay) {
// return setTimeout(function() {
// stopChannel(channel, id);
// }, delay * 1000)
// } else {
// stopChannel(channel, id);
// }
};
midi.chordOn = function(channel, chord, velocity, delay) {
for (var idx = 0; idx < chord.length; idx ++) {
var n = chord[idx];
var id = noteToKey[n];
if (!notes[id]) continue;
if (delay) {
return setTimeout(function() {
playChannel(channel, id);
}, delay * 1000);
} else {
playChannel(channel, id);
}
}
};
midi.chordOff = function(channel, chord, delay) {
for (var idx = 0; idx < chord.length; idx ++) {
var n = chord[idx];
var id = noteToKey[n];
if (!notes[id]) continue;
if (delay) {
return setTimeout(function() {
stopChannel(channel, id);
}, delay * 1000);
} else {
stopChannel(channel, id);
}
}
};
midi.stopAllNotes = function() {
for (var nid = 0, length = audioBuffers.length; nid < length; nid++) {
audioBuffers[nid].pause();
}
};
midi.connect = function(opts) {
root.setDefaultPlugin(midi);
///
for (var key in root.keyToNote) {
noteToKey[root.keyToNote[key]] = key;
notes[key] = {id: key};
}
///
opts.onsuccess && opts.onsuccess();
};
})();
})(MIDI);
/*
----------------------------------------------------------
Web Audio API - OGG or MPEG Soundbank
----------------------------------------------------------
http://webaudio.github.io/web-audio-api/
----------------------------------------------------------
*/