-
Notifications
You must be signed in to change notification settings - Fork 23
/
webmidi.js
4427 lines (3822 loc) · 155 KB
/
webmidi.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(scope) {
"use strict";
/**
* The `WebMidi` object makes it easier to work with the Web MIDI API. Basically, it simplifies
* two things: sending outgoing MIDI messages and reacting to incoming MIDI messages.
*
* Sending MIDI messages is done via an `Output` object. All available outputs can be accessed in
* the `WebMidi.outputs` array. There is one `Output` object for each output port available on
* your system. Similarly, reacting to MIDI messages as they are coming in is simply a matter of
* adding a listener to an `Input` object. Similarly, all inputs can be found in the
* `WebMidi.inputs` array.
*
* Please note that a single hardware device might create more than one input and/or output ports.
*
* #### Sending messages
*
* To send MIDI messages, you simply need to call the desired method (`playNote()`,
* `sendPitchBend()`, `stopNote()`, etc.) from an `Output` object and pass in the appropriate
* parameters. All the native MIDI communication will be handled for you. The only additional
* thing that needs to be done is to first enable `WebMidi`. Here is an example:
*
* WebMidi.enable(function(err) {
* if (err) console.log("An error occurred", err);
* WebMidi.outputs[0].playNote("C3");
* });
*
* The code above, calls the `WebMidi.enable()` method. Upon success, this method executes the
* callback function specified as a parameter. In this case, the callback calls the `playnote()`
* function to play a 3rd octave C on the first available output port.
*
* #### Receiving messages
*
* Receiving messages is just as easy. You simply have to set a callback function to be triggered
* when a specific MIDI message is received. For example, here"s how to listen for pitch bend
* events on the first input port:
*
* WebMidi.enable(function(err) {
* if (err) console.log("An error occurred", err);
*
* WebMidi.inputs[0].addListener("pitchbend", "all", function(e) {
* console.log("Pitch value: " + e.value);
* });
*
* });
*
* As you can see, this library is much easier to use than the native Web MIDI API. No need to
* manually craft or decode binary MIDI messages anymore!
*
* @class WebMidi
* @static
*
* @throws Error WebMidi is a singleton, it cannot be instantiated directly.
*
* @todo Switch away from yuidoc (deprecated) to be able to serve doc over https
* @todo Yuidoc does not allow multiple exceptions (@throws) for a single method ?!
*
*/
function WebMidi() {
// Singleton. Prevent instantiation through WebMidi.__proto__.constructor()
if (WebMidi.prototype._singleton) {
throw new Error("WebMidi is a singleton, it cannot be instantiated directly.");
}
WebMidi.prototype._singleton = this;
// MIDI inputs and outputs
this._inputs = [];
this._outputs = [];
// Object to hold all user-defined handlers for interface-wide events (connected, disconnected,
// etc.)
this._userHandlers = {};
// Array of statechange events to process. These events must be parsed synchronously so they do
// not override each other.
this._stateChangeQueue = [];
// Indicates whether we are currently processing a statechange event (in which case new events
// are to be queued).
this._processingStateChange = false;
// Events triggered at the interface level (WebMidi)
this._midiInterfaceEvents = ["connected", "disconnected"];
// the current nrpns being constructed, by channel
this._nrpnBuffer = [[],[],[],[], [],[],[],[], [],[],[],[], [],[],[],[]];
// Enable/Disable NRPN event dispatch
this._nrpnEventsEnabled = true;
// NRPN message types
this._nrpnTypes = ["entry", "increment", "decrement"];
// Notes and semitones for note guessing
this._notes = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
this._semitones = {C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 };
// Define some "static" properties
Object.defineProperties(this, {
/**
* [read-only] List of valid MIDI system messages and matching hexadecimal values.
*
* Note: values 249 and 253 are actually dispatched by the Web MIDI API but the MIDI 1.0 does
* not say what they are used for. About those values, it only states: undefined (reserved)
*
* @property MIDI_SYSTEM_MESSAGES
* @type Object
* @static
*
* @since 2.0.0
*/
MIDI_SYSTEM_MESSAGES: {
value: {
// System common messages
sysex: 0xF0, // 240
timecode: 0xF1, // 241
songposition: 0xF2, // 242
songselect: 0xF3, // 243
tuningrequest: 0xF6, // 246
sysexend: 0xF7, // 247 (never actually received - simply ends a sysex)
// System real-time messages
clock: 0xF8, // 248
start: 0xFA, // 250
continue: 0xFB, // 251
stop: 0xFC, // 252
activesensing: 0xFE, // 254
reset: 0xFF, // 255
// Custom WebMidi.js messages
midimessage: 0,
unknownsystemmessage: -1
},
writable: false,
enumerable: true,
configurable: false
},
/**
* [read-only] An object containing properties for each MIDI channel messages and their
* associated hexadecimal value.
*
* @property MIDI_CHANNEL_MESSAGES
* @type Object
* @static
*
* @since 2.0.0
*/
MIDI_CHANNEL_MESSAGES: {
value: {
noteoff: 0x8, // 8
noteon: 0x9, // 9
keyaftertouch: 0xA, // 10
controlchange: 0xB, // 11
channelmode: 0xB, // 11
nrpn: 0xB, // 11
programchange: 0xC, // 12
channelaftertouch: 0xD, // 13
pitchbend: 0xE // 14
},
writable: false,
enumerable: true,
configurable: false
},
/**
* [read-only] An object containing properties for each registered parameters and their
* associated pair of hexadecimal values. MIDI registered parameters extend the original list
* of control change messages (a.k.a. CC messages). Currently, there are only a limited number
* of them.
*
* @property MIDI_REGISTERED_PARAMETER
* @type Object
* @static
*
* @since 2.0.0
*/
MIDI_REGISTERED_PARAMETER: {
value: {
pitchbendrange: [0x00, 0x00],
channelfinetuning: [0x00, 0x01],
channelcoarsetuning: [0x00, 0x02],
tuningprogram: [0x00, 0x03],
tuningbank: [0x00, 0x04],
modulationrange: [0x00, 0x05],
azimuthangle: [0x3D, 0x00],
elevationangle: [0x3D, 0x01],
gain: [0x3D, 0x02],
distanceratio: [0x3D, 0x03],
maximumdistance: [0x3D, 0x04],
maximumdistancegain: [0x3D, 0x05],
referencedistanceratio: [0x3D, 0x06],
panspreadangle: [0x3D, 0x07],
rollangle: [0x3D, 0x08]
},
writable: false,
enumerable: true,
configurable: false
},
/**
* [read-only] An object containing properties for each MIDI control change messages (a.k.a.
* CC messages) and their associated hexadecimal value.
*
* @property MIDI_CONTROL_CHANGE_MESSAGES
* @type Object
* @static
*
* @since 2.0.0
*/
MIDI_CONTROL_CHANGE_MESSAGES: {
value: {
bankselectcoarse: 0,
modulationwheelcoarse: 1,
breathcontrollercoarse: 2,
footcontrollercoarse: 4,
portamentotimecoarse: 5,
dataentrycoarse: 6,
volumecoarse: 7,
balancecoarse: 8,
pancoarse: 10,
expressioncoarse: 11,
effectcontrol1coarse: 12,
effectcontrol2coarse: 13,
generalpurposeslider1: 16,
generalpurposeslider2: 17,
generalpurposeslider3: 18,
generalpurposeslider4: 19,
bankselectfine: 32,
modulationwheelfine: 33,
breathcontrollerfine: 34,
footcontrollerfine: 36,
portamentotimefine: 37,
dataentryfine: 38,
volumefine: 39,
balancefine: 40,
panfine: 42,
expressionfine: 43,
effectcontrol1fine: 44,
effectcontrol2fine: 45,
holdpedal: 64,
portamento: 65,
sustenutopedal: 66,
softpedal: 67,
legatopedal: 68,
hold2pedal: 69,
soundvariation: 70,
resonance: 71,
soundreleasetime: 72,
soundattacktime: 73,
brightness: 74,
soundcontrol6: 75,
soundcontrol7: 76,
soundcontrol8: 77,
soundcontrol9: 78,
soundcontrol10: 79,
generalpurposebutton1: 80,
generalpurposebutton2: 81,
generalpurposebutton3: 82,
generalpurposebutton4: 83,
reverblevel: 91,
tremololevel: 92,
choruslevel: 93,
celestelevel: 94,
phaserlevel: 95,
databuttonincrement: 96,
databuttondecrement: 97,
nonregisteredparametercoarse: 98,
nonregisteredparameterfine: 99,
registeredparametercoarse: 100,
registeredparameterfine: 101
},
writable: false,
enumerable: true,
configurable: false
},
/**
* [read-only] An object containing properties for MIDI control change messages
* that make up NRPN messages
*
* @property MIDI_NRPN_MESSAGES
* @type Object
* @static
*
* @since 2.0.0
*/
MIDI_NRPN_MESSAGES: {
value: {
entrymsb: 6,
entrylsb: 38,
increment: 96,
decrement: 97,
paramlsb: 98,
parammsb: 99,
nullactiveparameter: 127
},
writable: false,
enumerable: true,
configurable: false
},
/**
* [read-only] List of MIDI channel mode messages as defined in the official MIDI
* specification.
*
* @property MIDI_CHANNEL_MODE_MESSAGES
* @type Object
* @static
*
* @since 2.0.0
*/
MIDI_CHANNEL_MODE_MESSAGES: {
value: {
allsoundoff: 120,
resetallcontrollers: 121,
localcontrol: 122,
allnotesoff: 123,
omnimodeoff: 124,
omnimodeon: 125,
monomodeon: 126,
polymodeon: 127
},
writable: false,
enumerable: true,
configurable: false
},
/**
* An integer to offset the octave both in inbound and outbound messages. By default, middle C
* (MIDI note number 60) is placed on the 4th octave (C4).
*
* If, for example, `octaveOffset` is set to 2, MIDI note number 60 will be reported as C6. If
* `octaveOffset` is set to -1, MIDI note number 60 will be reported as C3.
*
* @property octaveOffset
* @type Number
* @static
*
* @since 2.1
*/
octaveOffset: {
value: 0,
writable: true,
enumerable: true,
configurable: false
}
});
// Define getters/setters
Object.defineProperties(this, {
/**
* [read-only] Indicates whether the environment supports the Web MIDI API or not.
*
* Note: in environments that do not offer built-in MIDI support, this will report true if the
* `navigator.requestMIDIAccess` function is available. For example, if you have installed
* WebMIDIAPIShim but no plugin, this property will be true even though actual support might
* not be there.
*
* @property supported
* @type Boolean
* @static
*/
supported: {
enumerable: true,
get: function() {
return "requestMIDIAccess" in navigator;
}
},
/**
* [read-only] Indicates whether the interface to the host"s MIDI subsystem is currently
* enabled.
*
* @property enabled
* @type Boolean
* @static
*/
enabled: {
enumerable: true,
get: function() {
return this.interface !== undefined;
}.bind(this)
},
/**
* [read-only] An array of all currently available MIDI input ports.
*
* @property inputs
* @type {Array}
* @static
*/
inputs: {
enumerable: true,
get: function() {
return this._inputs;
}.bind(this)
},
/**
* [read-only] An array of all currently available MIDI output ports.
*
* @property outputs
* @type {Array}
* @static
*/
outputs: {
enumerable: true,
get: function() {
return this._outputs;
}.bind(this)
},
/**
* [read-only] Indicates whether the interface to the host"s MIDI subsystem is currently
* active.
*
* @property sysexEnabled
* @type Boolean
* @static
*/
sysexEnabled: {
enumerable: true,
get: function() {
return !!(this.interface && this.interface.sysexEnabled);
}.bind(this)
},
/**
* [read-only] Indicates whether WebMidi should dispatch Non-Registered
* Parameter Number events (which are generally groups of CC messages)
* If correct sequences of CC messages are received, NRPN events will
* fire. The first out of order NRPN CC will fall through the collector
* logic and all CC messages buffered will be discarded as incomplete.
*
* @private
*
* @property nrpnEventsEnabled
* @type Boolean
* @static
*/
nrpnEventsEnabled: {
enumerable: true,
get: function() {
return !!(this._nrpnEventsEnabled);
}.bind(this),
set: function(enabled) {
this._nrpnEventsEnabled = enabled;
return this._nrpnEventsEnabled;
}
},
/**
* [read-only] NRPN message types
*
* @property nrpnTypes
* @type Array
* @static
*/
nrpnTypes: {
enumerable: true,
get: function() {
return this._nrpnTypes;
}.bind(this)
},
/**
* [read-only] Current MIDI performance time in milliseconds. This can be used to queue events
* in the future.
*
* @property time
* @type DOMHighResTimeStamp
* @static
*/
time: {
enumerable: true,
get: function() {
return performance.now();
}
}
});
}
// WebMidi is a singleton so we instantiate it ourselves and keep it in a var for internal
// reference.
var wm = new WebMidi();
/**
* Checks if the Web MIDI API is available and then tries to connect to the host's MIDI subsystem.
* This is an asynchronous operation. When it's done, the specified handler callback will be
* executed. If an error occurred, the callback function will receive an `Error` object as its
* sole parameter.
*
* To enable the use of system exclusive messages, the `sysex` parameter should be set to true.
* However, under some environments (e.g. Jazz-Plugin), the sysex parameter is ignored and sysex
* is always enabled.
*
* Warning: starting with Chrome v77, the Web MIDI API must be hosted on a secure origin
* (`https://`, `localhost` or `file:///`) and the user will always be prompted to authorize the
* operation (no matter if `sysex` is requested or not).
*
* @method enable
* @static
*
* @param [callback] {Function} A function to execute upon success. This function will receive an
* `Error` object upon failure to enable the Web MIDI API.
* @param [sysex=false] {Boolean} Whether to enable MIDI system exclusive messages or not.
*
* @throws Error The Web MIDI API is not supported by your browser.
* @throws Error Jazz-Plugin must be installed to use WebMIDIAPIShim.
*/
WebMidi.prototype.enable = function(callback, sysex) {
// Why are you not using a Promise-based API for the enable() method?
//
// Short answer: because of IE.
//
// Long answer:
//
// IE 11 and below still do not support promises. Therefore, WebMIDIAPIShim has to implement a
// simple Promise look-alike object to handle the call to requestMIDIAccess(). This look-alike
// is not a fully-fledged Promise object. It does not support using catch() for example. This
// means that, to provide a real Promise-based interface for the enable() method, we would need
// to add a dependency in the form of a Promise polyfill. So, to keep things simpler, we will
// stick to the good old callback based enable() function.
if (this.enabled) return;
if ( !this.supported) {
if (typeof callback === "function") {
callback( new Error("The Web MIDI API is not supported by your browser.") );
}
return;
}
navigator.requestMIDIAccess({sysex: sysex}).then(
function(midiAccess) {
var events = [],
promises = [],
promiseTimeout;
this.interface = midiAccess;
this._resetInterfaceUserHandlers();
// We setup a temporary `statechange` handler that will catch all events triggered while we
// setup. Those events will be re-triggered after calling the user"s callback. This will
// allow the user to listen to "connected" events which can be very convenient.
this.interface.onstatechange = function (e) {
events.push(e);
};
// Here we manually open the inputs and outputs. Usually, this is optional. When the ports
// are not explicitely opened, they will be opened automatically (and asynchonously) by
// setting a listener on `midimessage` (MIDIInput) or calling `send()` (MIDIOutput).
// However, we do not want that here. We want to be sure that "connected" events will be
// available in the user"s callback. So, what we do is open all input and output ports and
// wait until all promises are resolved. Then, we re-trigger the events after the user"s
// callback has been executed. This seems like the most sensible and practical way.
var inputs = midiAccess.inputs.values();
for (var input = inputs.next(); input && !input.done; input = inputs.next()) {
promises.push(input.value.open());
}
var outputs = midiAccess.outputs.values();
for (var output = outputs.next(); output && !output.done; output = outputs.next()) {
promises.push(output.value.open());
}
// Since this library might be used in environments without support for promises (such as
// Jazz-Midi) or in environments that are not properly opening the ports (such as Web MIDI
// Browser), we fall back to a timer-based approach if the promise-based approach fails.
function onPortsOpen() {
clearTimeout(promiseTimeout);
this._updateInputsAndOutputs();
this.interface.onstatechange = this._onInterfaceStateChange.bind(this);
// We execute the callback and then re-trigger the statechange events.
if (typeof callback === "function") { callback.call(this); }
events.forEach(function (event) {
this._onInterfaceStateChange(event);
}.bind(this));
}
promiseTimeout = setTimeout(onPortsOpen.bind(this), 200);
if (Promise) {
Promise
.all(promises)
.catch(function(err) { console.warn(err); })
.then(onPortsOpen.bind(this));
}
// When MIDI access is requested, all input and output ports have their "state" set to
// "connected". However, the value of their "connection" property is "closed".
//
// A `MIDIInput` becomes `open` when you explicitely call its `open()` method or when you
// assign a listener to its `onmidimessage` property. A `MIDIOutput` becomes `open` when you
// use the `send()` method or when you can explicitely call its `open()` method.
//
// Calling `_updateInputsAndOutputs()` attaches listeners to all inputs. As per the spec,
// this triggers a `statechange` event on MIDIAccess.
}.bind(this),
function (err) {
if (typeof callback === "function") { callback.call(this, err); }
}.bind(this)
);
};
/**
* Completely disables `WebMidi` by unlinking the MIDI subsystem's interface and destroying all
* `Input` and `Output` objects that may be available. This also means that any listener(s) that
* may have been defined on `WebMidi` or any `Input` objects will be destroyed.
*
* @method disable
* @static
*
* @since 2.0.0
*/
WebMidi.prototype.disable = function() {
if ( !this.supported ) {
throw new Error("The Web MIDI API is not supported by your browser.");
}
if (this.enabled) {
this.removeListener();
this.inputs.forEach(function (input) {
input.removeListener();
});
}
if (this.interface) this.interface.onstatechange = undefined;
this.interface = undefined; // also resets enabled, sysexEnabled, nrpnEventsEnabled
this._inputs = [];
this._outputs = [];
this._nrpnEventsEnabled = true;
this._resetInterfaceUserHandlers();
};
/**
* Adds an event listener on the `WebMidi` object that will trigger a function callback when the
* specified event happens.
*
* WebMidi must be enabled before adding event listeners.
*
* Currently, only one event is being dispatched by the `WebMidi` object:
*
* * {{#crossLink "WebMidi/statechange:event"}}statechange{{/crossLink}}
*
* @method addListener
* @static
* @chainable
*
* @param type {String} The type of the event.
*
* @param listener {Function} A callback function to execute when the specified event is detected.
* This function will receive an event parameter object. For details on this object"s properties,
* check out the documentation for the various events (links above).
*
* @throws {Error} WebMidi must be enabled before adding event listeners.
* @throws {TypeError} The specified event type is not supported.
* @throws {TypeError} The "listener" parameter must be a function.
*
* @return {WebMidi} Returns the `WebMidi` object so methods can be chained.
*/
WebMidi.prototype.addListener = function(type, listener) {
if (!this.enabled) {
throw new Error("WebMidi must be enabled before adding event listeners.");
}
if (typeof listener !== "function") {
throw new TypeError("The 'listener' parameter must be a function.");
}
if (this._midiInterfaceEvents.indexOf(type) >= 0) {
this._userHandlers[type].push(listener);
} else {
throw new TypeError("The specified event type is not supported.");
}
return this;
};
/**
* Checks if the specified event type is already defined to trigger the specified listener
* function.
*
* @method hasListener
* @static
*
* @param {String} type The type of the event.
* @param {Function} listener The callback function to check for.
*
* @throws {Error} WebMidi must be enabled before checking event listeners.
* @throws {TypeError} The "listener" parameter must be a function.
* @throws {TypeError} The specified event type is not supported.
*
* @return {Boolean} Boolean value indicating whether or not a callback is already defined for
* this event type.
*/
WebMidi.prototype.hasListener = function(type, listener) {
if (!this.enabled) {
throw new Error("WebMidi must be enabled before checking event listeners.");
}
if (typeof listener !== "function") {
throw new TypeError("The 'listener' parameter must be a function.");
}
if (this._midiInterfaceEvents.indexOf(type) >= 0) {
for (var o = 0; o < this._userHandlers[type].length; o++) {
if (this._userHandlers[type][o] === listener) {
return true;
}
}
} else {
throw new TypeError("The specified event type is not supported.");
}
return false;
};
/**
* Removes the specified listener(s). If the `listener` parameter is left undefined, all listeners
* for the specified `type` will be removed. If both the `listener` and the `type` parameters are
* omitted, all listeners attached to the `WebMidi` object will be removed.
*
* @method removeListener
* @static
* @chainable
*
* @param {String} [type] The type of the event.
* @param {Function} [listener] The callback function to check for.
*
* @throws {Error} WebMidi must be enabled before removing event listeners.
* @throws {TypeError} The "listener" parameter must be a function.
* @throws {TypeError} The specified event type is not supported.
*
* @return {WebMidi} The `WebMidi` object for easy method chaining.
*/
WebMidi.prototype.removeListener = function(type, listener) {
if (!this.enabled) {
throw new Error("WebMidi must be enabled before removing event listeners.");
}
if (listener !== undefined && typeof listener !== "function") {
throw new TypeError("The 'listener' parameter must be a function.");
}
if (this._midiInterfaceEvents.indexOf(type) >= 0) {
if (listener) {
for (var o = 0; o < this._userHandlers[type].length; o++) {
if (this._userHandlers[type][o] === listener) {
this._userHandlers[type].splice(o, 1);
}
}
} else {
this._userHandlers[type] = [];
}
} else if (type === undefined) {
this._resetInterfaceUserHandlers();
} else {
throw new TypeError("The specified event type is not supported.");
}
return this;
};
/**
* Returns a sanitized array of valid MIDI channel numbers (1-16). The parameter should be one of
* the following:
*
* * a single integer
* * an array of integers
* * the special value `"all"`
* * the special value `"none"`
*
* Passing `"all"` or `undefined` as a parameter to this function results in all channels being
* returned (1-16). Passing `"none"` results in no channel being returned (as an empty array).
*
* Note: parameters that cannot successfully be parsed to integers between 1 and 16 are silently
* ignored.
*
* @method toMIDIChannels
* @static
*
* @param [channel="all"] {Number|Array|"all"|"none"}
* @returns {Array} An array of 0 or more valid MIDI channel numbers
*/
WebMidi.prototype.toMIDIChannels = function(channel) {
var channels;
if (channel === "all" || channel === undefined) {
channels = ["all"];
} else if (channel === "none") {
channels = [];
return channels;
} else if (!Array.isArray(channel)) {
channels = [channel];
} else {
channels = channel;
}
// In order to preserve backwards-compatibility, we let this assignment as it is.
if (channels.indexOf("all") > -1) {
channels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
}
return channels
.map(function(ch) {
return parseInt(ch);
})
.filter(function(ch) {
return (ch >= 1 && ch <= 16);
});
};
/**
*
* Returns the `Input` object that matches the specified ID string or `false` if no matching input
* is found. As per the Web MIDI API specification, IDs are strings (not integers).
*
* Please note that IDs change from one host to another. For example, Chrome does not use the same
* kind of IDs as Jazz-Plugin.
*
* @method getInputById
* @static
*
* @param id {String} The ID string of the port. IDs can be viewed by looking at the
* `WebMidi.inputs` array.
*
* @returns {Input|false} A MIDIInput port matching the specified ID string. If no matching port
* can be found, the method returns `false`.
*
* @throws Error WebMidi is not enabled.
*
* @since 2.0.0
*/
WebMidi.prototype.getInputById = function(id) {
if (!this.enabled) throw new Error("WebMidi is not enabled.");
id = String(id);
for (var i = 0; i < this.inputs.length; i++) {
if (this.inputs[i].id === id) return this.inputs[i];
}
return false;
};
/**
* Returns the `Output` object that matches the specified ID string or `false` if no matching
* output is found. As per the Web MIDI API specification, IDs are strings (not integers).
*
* Please note that IDs change from one host to another. For example, Chrome does not use the same
* kind of IDs as Jazz-Plugin.
*
* @method getOutputById
* @static
*
* @param id {String} The ID string of the port. IDs can be viewed by looking at the
* `WebMidi.outputs` array.
*
* @returns {Output|false} A MIDIOutput port matching the specified ID string. If no matching port
* can be found, the method returns `false`.
*
* @throws Error WebMidi is not enabled.
*
* @since 2.0.0
*/
WebMidi.prototype.getOutputById = function(id) {
if (!this.enabled) throw new Error("WebMidi is not enabled.");
id = String(id);
for (var i = 0; i < this.outputs.length; i++) {
if (this.outputs[i].id === id) return this.outputs[i];
}
return false;
};
/**
* Returns the first MIDI `Input` whose name *contains* the specified string.
*
* Please note that the port names change from one host to another. For example, Chrome does
* not report port names in the same way as the Jazz-Plugin does.
*
* @method getInputByName
* @static
*
* @param name {String} The name of a MIDI input port such as those visible in the
* `WebMidi.inputs` array.
*
* @returns {Input|False} The `Input` that was found or `false` if no input matched the specified
* name.
*
* @throws Error WebMidi is not enabled.
* @throws TypeError The name must be a string.
*
* @since 2.0.0
*/
WebMidi.prototype.getInputByName = function(name) {
if (!this.enabled) {
throw new Error("WebMidi is not enabled.");
}
for (var i = 0; i < this.inputs.length; i++) {
if (~this.inputs[i].name.indexOf(name)) { return this.inputs[i]; }
}
return false;
};
/**
* Returns the octave number for the specified MIDI note number (0-127). By default, the value is
* based on middle C (note number 60) being placed on the 4th octave (C4). However, by using the
* <a href="#property_octaveOffset">octaveOffset</a> property, you can offset the result as much
* as you want.
*
* @method getOctave
* @static
*
* @param number {Number} An integer representing a valid MIDI note number (between 0 and 127).
*
* @returns {Number} The octave (as a signed integer) or `undefined`.
*
* @since 2.0.0-rc.6
*/
WebMidi.prototype.getOctave = function(number) {
if (number != null && number >= 0 && number <= 127) {
return Math.floor(Math.floor(number) / 12 - 1) + Math.floor(wm.octaveOffset);
}
};
/**
* Returns the first MIDI `Output` that matches the specified name.
*
* Please note that the port names change from one host to another. For example, Chrome does
* not report port names in the same way as the Jazz-Plugin does.
*
* @method getOutputByName
* @static
*
* @param name {String} The name of a MIDI output port such as those visible in the
* `WebMidi.outputs` array.
*
* @returns {Output|False} The `Output` that was found or `false` if no output matched the
* specified name.
*