forked from WebAudio/web-midi-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
1114 lines (994 loc) · 63.9 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<title>Web MIDI API</title>
<meta charset="utf-8" />
<!--
=== NOTA BENE ===
For the three scripts below, if your spec resides on dev.w3 you can check them
out in the same tree and use relative links so that they'll work offline,
-->
<script src='https://www.w3.org/Tools/respec/respec-w3c-common' class='remove'></script>
<script class='remove'>
var respecConfig = {
shortName: "webmidi",
specStatus: "WD",
copyrightStart: "2015",
edDraftURI: "https://webaudio.github.io/web-midi-api/",
editors: [
{ name: "Chris Wilson",
url: "mailto:[email protected]",
w3cid: "3742",
company: "Google",
companyURL: "http://google.com"
},
{ name: "Jussi Kalliokoski",
url: "http://juss.in",
w3cid: "45545"
},
],
otherLinks: [{
key: "Versioning Repository",
href: "https://github.com/WebAudio/web-midi-api/",
}, {
key: "Issues tracker",
href: "https://github.com/WebAudio/web-midi-api/issues?state=open"
}, {
key: "Feedback email list",
href: "mailto:[email protected]"
}
],
wg: "Audio Working Group",
wgURI: "http://www.w3.org/2011/audio/",
wgPublicList: "public-audio",
wgPatentURI: "http://www.w3.org/2004/01/pp-impl/46884/status",
previousPublishDate: "2013-11-26",
previousMaturity: "WD"
};
</script>
</head>
<body>
<section id="abstract">
<p>
Some user agents have music devices, such as synthesizers,
keyboard and other controllers, and drum machines connected to their host computer or device. The widely adopted
Musical Instrument Digital Interface (MIDI) protocol enables
electronic musical instruments, controllers and computers to
communicate and synchronize with each other. MIDI does not transmit
audio signals: instead, it sends event messages about musical notes,
controller signals for parameters such as volume, vibrato and panning,
cues and clock signals to set the tempo, and system-specific MIDI
communications (e.g. to remotely store synthesizer-specific patch
data). This same protocol has become a standard for non-musical uses,
such as show control, lighting and special effects control.
</p>
<p>
This specification defines an API supporting the MIDI protocol, enabling web applications to enumerate and select MIDI input and output devices on the client system and send and receive MIDI messages. It is intended to enable non-music MIDI applications as well as music ones, by providing low-level access to the MIDI devices available on the users' systems. The Web MIDI API is not intended to describe music or controller inputs semantically; it is designed to expose the mechanics of MIDI input and output interfaces, and the practical aspects of sending and receiving MIDI messages, without identifying what those actions might mean semantically (e.g., in terms of "modulate the vibrato by 20Hz" or "play a G#7 chord", other than in terms of changing a controller value or sending a set of note-on messages that happen to represent a G#7 chord).
</p>
<p>
To some users, "MIDI" has become synonymous with Standard MIDI Files and General MIDI. That is not the intent of this API; the use case of simply playing back a .SMF file is not within the purview of this specification (it could be considered a different format to be supported by the HTML5 <code><audio></code> element, for example). The Web MIDI API is intended to enable direct access to devices that respond to MIDI - external synthesizers or lighting systems, for example, or even the software synthesizers that are built in to many common operating systems. The Web MIDI API is also explicitly designed to enable a new class of applications on the web that can respond to MIDI controller inputs - using external hardware controllers with physical buttons, knobs and sliders (as well as musical controllers like keyboard, guitar or wind instrument controllers) to control web applications.
</p>
<p>
The Web MIDI API is also expected to be used in conjunction with other APIs and elements of the web platform, notably the Web Audio API. This API is also intended to be familiar to users of MIDI APIs on other systems, such as Apple's CoreMIDI and Microsoft's Windows MIDI API.
</p>
</section>
<section class="informative">
<h2>Introduction</h2>
<p>
The Web MIDI API specification defines a means for web developers to
enumerate, manipulate and access MIDI devices - for example interfaces that may provide hardware MIDI ports with other devices plugged in to them and USB devices that support the USB-MIDI specification. Having a Web API for MIDI enables web applications that use existing software and
hardware synthesizers, hardware music controllers and light systems and other mechanical
apparatus controlled by MIDI. This API has been defined with this wide variety of use cases in mind.
</p>
<p>
The approaches taken by this API are similar to those taken in Apple's CoreMIDI API and Microsoft's Windows MIDI API; that is, the API is designed to represent the low-level software protocol of MIDI, in order to enable developers to build powerful MIDI software on top. The API enables the developer to enumerate input and output interfaces, and send and receive MIDI messages, but (similar to the aforementioned APIs) it does not attempt to semantically define or interpret MIDI messages beyond what is necessary to robustly support current devices.
</p>
<p>
The Web MIDI API is not intended to directly implement high-level concepts such as sequencing; it does not directly support Standard MIDI Files, for example, although a Standard MIDI File player can be built on top of the Web MIDI API. It is also not intended to semantically capture patches or controller assignments, as General MIDI does; such interpretation is outside the scope of the Web MIDI API (though again, General MIDI can easily be utilized through the Web MIDI API).
</p>
</section>
<section id="sotd">
</section>
<section id="conformance">
<p>
This specification defines conformance criteria that apply to a single
product: the <dfn>user agent</dfn> that implements the
interfaces that it contains.
</p>
<p>
Implementations that use ECMAScript to implement the APIs defined in
this specification MUST implement them in a manner consistent with the
ECMAScript Bindings defined in the Web IDL specification [[!WEBIDL]],
as this specification uses that specification and terminology.
</p>
</section>
<section>
<h2>Terminology</h2>
<p>
The concepts <dfn><a href="http://dev.w3.org/html5/spec/webappapis.html#queue-a-task">
queue a task</a></dfn> and
<dfn><a href="http://dev.w3.org/html5/spec/webappapis.html#fire-a-simple-event">
fires a simple event</a></dfn> are defined in [[!HTML5]].
</p>
<p>
The terms <dfn><a href="http://dev.w3.org/html5/spec/webappapis.html#event-handlers">
event handlers</a></dfn> and
<dfn><a href="http://dev.w3.org/html5/spec/webappapis.html#event-handler-event-type">
event handler event types</a></dfn> and corresponding <a href="http://www.w3.org/html/wg/drafts/html/master/single-page.html#eventhandler"><code>EventHandler</code></a> interface are defined in [[!HTML5]]. </p>
<p>
The term <dfn id="OctetDfn"><a href="http://www.w3.org/TR/WebIDL/#idl-octet">octet</a></dfn> is defined in [[!WEBIDL]].
</p>
<p>
The <dfn id="WebAudio">Web Audio API</dfn> and its associated interfaces and concepts are defined in [[!webaudio]].
</p>
<p>
The <a href="http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html/#interface-event"><dfn title=
"Event">Event</dfn></a> interface
is defined in [[!DOM4]].
</p>
<p>The <a href="http://www.w3.org/TR/DOM-Level-3-Core/core.html#ERROR-Interfaces-DOMError"><dfn title="DOMError">DOMError</dfn></a> interface is defined in [[!DOM-LEVEL-3-CORE]].
<p>
The <dfn id="DomHighResTimeStampDfn"><a href=
"http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/HighResolutionTime/Overview.html#sec-DOMHighResTimeStamp"
>DOMHighResTimeStamp</a></dfn> interface is defined in [[!HIGHRES-TIME]].
</p>
<p>
The terms <dfn>MIDI</dfn>, <dfn>MIDI device</dfn>, <dfn>MIDI input port</dfn>, <dfn>MIDI output port</dfn>, <dfn>MIDI interface</dfn>, <dfn>MIDI message</dfn>, <dfn>MIDI System Real-Time message</dfn> and <dfn>system exclusive</dfn> are defined in [[!MIDI]].
<p>
The <dfn><a href="http://dom.spec.whatwg.org/#promises">Promise</a></dfn> interface is currently defined in <a href="http://dom.spec.whatwg.org/">the WHATWG DOM specification</a>.
<!-- FIXME: This list is not exhaustive. -->
</section>
<section>
<h2>Obtaining Access to MIDI Devices</h2>
<section>
<h2 id="requestMIDIAccess">requestMIDIAccess()</h2>
<dl class="idl"
title="partial interface Navigator">
<dt>Promise<MIDIAccess> requestMIDIAccess( optional MIDIOptions options )</dt>
<dd>
<p>
When invoked, returns a Promise object representing a request for access to MIDI devices on the user's system.
</p>
<p>
Requesting MIDI access SHOULD prompt the user for access to MIDI devices,
particularly if system exclusive access is requested. In some
scenarios, this permission may have already been implicitly or
explicitly granted, in which case this prompt may not appear.
If the user gives express permission or the call is otherwise
approved, the vended Promise's <var>resolveCallback</var> is invoked, as a <code><a>MIDISuccessCallback</a></code> (i.e., with a
<code><a>MIDIAccess</a></code> object and a <code><a>MIDIOptions</a></code> object as its arguments. The
underlying system may choose to allow the user to select
specific MIDI interfaces to expose to this API (i.e. pick
and choose interfaces on an individual basis), although
this is not required. The system may also choose to prompt
(or not) based on whether system exclusive support is
requested, as system exclusive has greater privacy and
security implications.</p>
<p>If the user declines or the call is denied for any other reason, the Promise's
<var>rejectCallback</var> (if any) is invoked with a <code><a>DOMException</a></code> parameter.
</p>
<p>
When the <dfn id="dom-navigator-requestmidiaccess">
<code>requestMIDIAccess</code></dfn> method is called, the user
agent MUST run the <dfn>algorithm to request MIDI Access</dfn>:
</p>
<ol>
<li><p>Let <var>promise</var> be a new Promise object and <var>resolver</var> be its associated resolver.</p></li>
<li><p>Return <var>promise</var> and run the following steps asynchronously.</p></li>
<li><p>
Optionally, e.g. based on a previously-established user
preference, for security reasons, or due to platform
limitations, jump to the step labeled <em>failure</em>
below.
</p></li>
<li><p>
Optionally, e.g. based on a previously-established user
preference, jump to the step labeled <em>success</em>
below.
</p></li>
<li><p>
Prompt the user in a user-agent-specific manner for
permission to provide the entry script's origin with a
<code><a>MIDIAccess</a></code> object representing
control over user's MIDI devices. This prompt may
be contingent upon whether system exclusive support was
requested, and may allow the user to enable or disable
that access.
</p>
<p>
If permission is denied, jump to the step labeled
<em>failure</em> below. If the user never responds, this
algorithm will never progress beyond this step. If
permission is granted, continue the following steps.
</p>
</li>
<li><p><em><b>success</b></em>: Let <var>access</var> be a new <code><a>MIDIAccess</a></code> object. (It is possible to call requestMIDIAccess() multiple times; this may prompt the user multiple times, so it may not be best practice, and the same instance of MIDIAccess will not be returned each time.)</p></li>
<li><p>Call <var>resolver</var>'s <code>accept(value)</code> method with <var>access</var> as value argument.</p></li>
<li><p>Terminate these steps.</p></li>
<li><p><em><b>failure</b></em>: Let <var>error</var> be a new <code><a>DOMException</a></code>.
This exception's .name should be <code>"SecurityError"</code> if the
user or their security settings denied the application from creating a MIDIAccess instance with the requested options, <code>"AbortError"</code> if the page is going to be closed for a user navigation, <code>"InvalidStateError"</code> if the underlying systems raise any errors, or otherwise it should be <code>"NotSupportedError"</code>.</p></li>
<li><p>Call <var>resolver</var>'s <code>reject(value)</code> method with <var>error</var> as value argument.</p></li>
</ol>
</dd>
</dl>
</section>
<section>
<h2 id="MIDIOptions"><a>MIDIOptions</a> dictionary</h2>
<p>This dictionary contains optional settings that may be provided to the requestMIDIAccess request.</p>
<dl class="idl"
title="dictionary MIDIOptions">
<dt>boolean sysex</dt>
<dd>
<p>This member informs the system whether the ability to send and receive system exclusive messages is requested or allowed on a given <a>MIDIAccess</a> object. On the option passed to <code><a>requestMIDIAccess</a></code>, if this member is set to true, but system exclusive support is denied (either by policy or by user action), the access request will fail with a <code>"SecurityError"</code> error. If this support is not requested (and allowed), the system will throw exceptions if the user tries to send system exclusive messages, and will silently mask out any system exclusive messages received on the port.</p>
<p>In the <code>options</code> parameter passed to the resolveCallback, this member indicates whether system exclusive is allowed on the MIDIAccess.</p>
</dd>
</dl>
</section>
<section>
<h3 id="MIDIInputMap"><a>MIDIInputMap</a> Interface</h3>
<dl title="interface MIDIInputMap" class="idl">
<dt>readonly maplike<DOMString, MIDIInput></dt>
<dd>This is a maplike interface whose value is a MIDIInput instance and key is its ID.</dd>
</dl>
<p>This type is used to represent all the currently available MIDI input ports. This enables
<pre> // to tell how many entries there are:
var numberOfMIDIInputs = inputs.size;
// add each of the ports to a <select> box
inputs.forEach( function( key, port ) {
var opt = document.createElement("option");
opt.text = port.name;
document.getElementById("inputportselector").add(opt);
});
// or you could express in ECMAScript 6 as:
for (let input of inputs.values()) {
var opt = document.createElement("option");
opt.text = input.name;
document.getElementById("inputportselector").add(opt);
}</pre>
</section>
<section>
<h3 id="MIDIOutputMap"><a>MIDIOutputMap</a> Interface</h3>
<dl title="interface MIDIOutputMap" class="idl">
<dt>readonly maplike<DOMString, MIDIOutput></dt>
<dd>This is a maplike interface whose value is a MIDIOutput instance and key is its ID.</dd>
</dl>
<p>This type is used to represent all the currently available MIDI output ports. This enables
<pre> // to tell how many entries there are:
var numberOfMIDIOutputs = outputs.size;
// add each of the ports to a <select> box
outputs.forEach( function( key, port ) {
var opt = document.createElement("option");
opt.text = port.name;
document.getElementById("outputportselector").add(opt);
});
// or you could express in ECMAScript 6 as:
for (output of outputs.values()) {
var opt = document.createElement("option");
opt.text = output.name;
document.getElementById("outputportselector").add(opt);
}</pre>
</section>
<section>
<h2><a>MIDISuccessCallback</a></h2>
<dl class="idl"
title="callback MIDISuccessCallback = void">
<dt>MIDIAccess access</dt>
<dd>
<p>
A <code><a>MIDIAccess</a></code> object created to provide
script access to the user's MIDI devices. This object is used
to enumerate and obtain access to individual MIDI devices.
<p><em>Note</em>: The term "MIDI device" in this specification
refers to a MIDI interface available to the host system; for
example, if a hardware MIDI adapter is connected to the host
system, it will be enumerated as a single device, even if
several MIDI-supporting devices (such as synthesizers or drum
machines) are plugged into hardware MIDI ports on the
adapter.
</dd>
<dt>MIDIOptions options</dt>
<dd>
<p>This parameter describes the options enabled on this <a>MIDIAccess</a> object.</p>
</dd>
</dl>
</section>
</section>
<section>
<h2 id="MIDIAccess"><a>MIDIAccess</a> Interface</h2>
<p>This interface provides the methods to list MIDI input and output
devices, and obtain access to an individual device.</p>
<dl title="interface MIDIAccess : EventTarget"
class="idl">
<dt>readonly attribute MIDIInputMap inputs</dt>
<dd>The MIDI input ports available to the system.</dd>
<dt>readonly attribute MIDIOutputMap outputs</dt>
<dd>The MIDI output ports available to the system.</dd>
<dt>attribute EventHandler onstatechange</dt>
<dd>
<p>The handler called when a new port is connected or an existing port changes the state attribute.</p>
<p>This <a>event handler</a>, of type <code><a href=
"#event-midiaccess-statechange">MIDIConnectionEvent</a></code>,
MUST be supported by all objects implementing the
<code><a>MIDIAccess</a></code> interface.
</p>
<p id="event-midiaccess-statechange">
Whenever a previously unavailable MIDI port becomes available for use, or an existing port changes the state attribute,
the user agent SHOULD run the following steps:</p>
<ol>
<li>Let <code>port</code> be the <code><a>MIDIPort</a></code> corresponding to the newly-available, or the existing port.</li>
<li>Let <code>event</code> be a newly constructed <code><a>MIDIConnectionEvent</a></code>, with the <code>port</code> attribute set to the port.</li>
<li>Fire an event named <code><a href="#event-midiaccess-statechange">statechange</a></code>at the <code>MIDIAccess</code>, using the <code>event</code> as the event object.</li>
</ol>
</dd>
<dt>readonly attribute boolean sysexEnabled</dt>
<dd>This attribute informs the user whether system exclusive support is enabled on this MIDIAccess.</dd>
</dl>
</section>
<section>
<h2 id="MIDIPort"><a>MIDIPort</a> Interface</h2>
<p>This interface represents a MIDI input or output port.</p>
<dl class="idl" title="enum MIDIPortType">
<dt>input</dt>
<dd>
If a MIDIPort is an input port, the type member MUST be this value.
</dd>
<dt>output</dt>
<dd>
If a MIDIPort is an output port, the type member MUST be this value.
</dd>
</dl>
<dl class="idl" title="enum MIDIPortDeviceState">
<dt>disconnected</dt>
<dd>
The device that MIDIPort represents is disconnected from the system. When a device is disconnected from the system, it should not appear in the relevant map of input and output ports.
</dd>
<dt>connected</dt>
<dd>
The device that MIDIPort represents is connected, and should appear in the map of input and output ports.
</dd>
</dl>
<dl class="idl" title="enum MIDIPortConnectionState">
<dt>open</dt>
<dd>
The device that MIDIPort represents has been opened (either <a href="#widl-MIDIPort-open-Promise-MIDIPort">implicitly or explicitly</a>) and is available for use.
</dd>
<dt>closed</dt>
<dd>
The device that MIDIPort represents has not been opened, or has been explicitly closed. Until a MIDIPort has been opened either explicitly (through <code><a href="#widl-MIDIPort-open-Promise-MIDIPort">open()</a></code>) or implicitly (by adding a <a href="#widl-MIDIInput-onmidimessage">midimessage</a> event handler on an input port, or calling <a href="#widl-MIDIOutput-send-void-sequence-octet--data-double-timestamp">send()</a> on an output port, this should be the default state of the device.
</dd>
<dt>pending</dt>
<dd>
The device that MIDIPort represents has been opened (either <a href="#widl-MIDIPort-open-Promise-MIDIPort">implicitly or explicitly</a>), but the device has subsequently been disconnected and is unavailable for use. If the device is reconnected, prior to sending a <code><a href="#widl-MIDIPort-onstatechange">statechange</a></code> event, the system should attempt to reopen the device (following the <a href="#dfn-algorithm-to-open-a-midiport">algorithm to open a MIDIPort</a>); this will result in either the connection state transitioning to "open" or to "closed".
</dd>
</dl>
<dl title="interface MIDIPort : EventTarget"
class="idl">
<dt>readonly attribute DOMString id</dt>
<dd>
<p>
A unique ID of the port. This can be used by developers to
remember ports the user has chosen for their application. The
User Agent MUST ensure that the <code><a>id</a></code>
is unique to only that port. The User Agent SHOULD ensure that
the id is maintained across instances of the
application - e.g., when the system is rebooted - and when a
device is removed from the system. Applications may want to
cache these ids locally to re-create a MIDI setup.
Some systems may not support completely unique persistent
identifiers; in such cases, it will be more challenging to
maintain identifiers when another interface is added or removed
from the system. (This might throw off the index of the
requested port.) It is expected that the system will do the
best it can to match a port across instances of the MIDI API:
for example, an implementation may opaquely use some form of
hash of the port interface manufacturer, name and
index as the id, so that a reference to that port id is likely
to match the port when plugged in. Applications may use the
comparison of id of MIDIPorts to test for equality.</p>
</dd>
<dt>readonly attribute DOMString? manufacturer</dt>
<dd>
<p>The manufacturer of the port.</p>
</dd>
<dt>readonly attribute DOMString? name</dt>
<dd>
<p>The system name of the port.</p>
</dd>
<dt>readonly attribute MIDIPortType type</dt>
<dd>
<p>
A descriptor property to distinguish whether the port is an
input or an output port.
For <code><a>MIDIOutput</a></code>,
this MUST be <code>"output"</code>.
For <code><a>MIDIInput</a></code>,
this MUST be <code>"input"</code>.
</p>
</dd>
<dt>readonly attribute DOMString? version</dt>
<dd>
<p>The version of the port.</p>
</dd>
<dt>readonly attribute MIDIPortDeviceState state</dt>
<dd>The state of the device.</dd>
<dt>readonly attribute MIDIPortConnectionState connection</dt>
<dd>The state of the connection to the device.</dd>
<dt>attribute EventHandler onstatechange</dt>
<dd>
<p>The handler called when an existing port changes its state or connection attributes.</p>
<p>This <a>event handler</a>, of type <code><a href=
"#event-midiport-statechange">statechange</a></code>,
MUST be supported by all objects implementing
<code><a>MIDIPort</a></code> interface.
</p>
</dd>
<dt>Promise<MIDIPort> open()</dt>
<dd>
<p>
Makes the MIDI device corresponding to the <a>MIDIPort</a> explicitly
available. Note that this call is NOT required in order to use the
<a>MIDIPort</a> - calling <code>send()</code> on a <a>MIDIOutput</a>
or attaching a MIDIMessageEvent handler on a <a>MIDIInputPort</a> will
cause an implicit open(). The underlying implementation may not need
to do anything in response to this call. However, some underlying
implementations may not be able to support shared access to MIDI devices,
so using explicit open() and close() calls will enable MIDI applications
to predictably control this exclusive access to devices.
</p>
<p>
When invoked, this method returns a Promise object representing a
request for access to the given MIDI port on the user's system.
</p>
<p>If the port device has a state of
<code><a href="#idl-def-MIDIPortDeviceState.connected">"connected"</a></code>,
when access to the port has been obtained (and the port is ready for
input or output), the vended Promise's <var>resolveCallback</var> is
invoked with a <code><a>MIDIPort</a></code> object as its argument.
</p>
<p>If access to a connected port is not available (for example, the port is
already in use in an exclusive-access-only platform), the Promise's
<var>rejectCallback</var> (if any) is invoked.
</p>
<p>If <code>open()</code> is called on a port that is
<code><a href="#idl-def-MIDIPortDeviceState.disconnected">"disconnected"</a></code>,
the port's <code><a href="">.connection</a></code> will transition to
<code><a href="#idl-def-MIDIPortConnectionState.pending">"pending"</a></code>,
until the port becomes <code><a href="#idl-def-MIDIPortDeviceState.connected">"connected"</a></code> or all references to it are dropped.
<p id="midiport-open-algorithm">
When this method is called, the user
agent MUST run the <dfn>algorithm to open a MIDIPort</dfn>:
</p>
<ol>
<li><p>Let <var>promise</var> be a new Promise object and
<var>resolver</var> be its associated resolver.</p></li>
<li><p>Return <var>promise</var> and run the following steps
asynchronously.</p></li>
<li><p>Let <var>port</var> be the given
<code><a href="#idl-def-MIDIPort">MIDIPort</a></code>
object.</p></li>
<li><p>If the device's connection is already <code><a
href="#idl-def-MIDIPortConnectionState.open">"open"</a></code>
(e.g. open() has already been called on this MIDIPort, or the
port has been implicitly opened), jump to the step labeled
<em>success</em> below.</p></li>
<li><p>If the device's connection is <code><a
href="#idl-def-MIDIPortConnectionState.pending">"pending"</a></code>
(i.e. the connection had been opened and the device was
subsequently disconnected), jump to the step labeled
<em>success</em> below.</p></li>
<li><p>If the device's state is <code><a
href="#idl-def-MIDIPortDeviceState.disconnected">"disconnected"</a></code>,
change the <code><a href="">connection</a></code> attribute of the
<code><a href="#idl-def-MIDIPort">MIDIPort</a></code> to
<code><a href="#idl-def-MIDIPortConnectionState.pending">"pending"</a></code>,
and enqueue a new <code><a
href="#idl-def-MIDIConnectionEvent">MIDIConnectionEvent</a></code>
to the <code><a href="#event-midiaccess-statechange">statechange</a></code>
handler of the <code><a>MIDIAccess</a></code> and to the
<code><a href="#event-midiport-statechange">statechange</a></code>
handler of the <code><a href="#idl-def-MIDIPort">MIDIPort</a></code>
and jump to the step labeled <em>success</em> below.</p></li>
<li><p>Attempt to obtain access to the given MIDI device in the
system. If the device is unavailable (e.g. is already in use by another
process and cannot be opened, or is disconnected), jump to the step labeled
<em>failure</em> below. If the device is available and access is
obtained, continue the following steps.</p></li>
<li><p>Change the <code>connection</code> attribute of the MIDIPort to
<code>"open"</code>, and enqueue a new <code><a>MIDIConnectionEvent</a></code>
to the <code><a href="#event-midiaccess-statechange">statechange</a></code>
handler of the <code><a>MIDIAccess</a></code> and to the
<code><a href="#event-midiport-statechange">statechange</a></code>
handler of the <code><a href="#idl-def-MIDIPort">MIDIPort</a></code>.</p></li>
<li><p>If this port is an output port and has any pending data
that is waiting to be sent, asynchronously begin sending that
data.</p></li>
<li><p><em><b>success</b></em>: Call <var>resolver</var>'s
<code>accept(value)</code> method with <var>port</var> as
value argument.</p></li>
<li><p>Terminate these steps.</p></li>
<li><p><em><b>failure</b></em>: Let <var>error</var> be a new
<code><a>DOMException</a></code>. This exception's .name should be
<code>"InvalidAccessError"</code> if the port is unavailable.</p></li>
<li><p>Call <var>resolver</var>'s <code>reject(value)</code> method
with <var>error</var> as value argument.</p></li>
</ol>
</dd>
<dt>Promise<MIDIPort> close()</dt>
<dd>
<p>
Makes the MIDI device corresponding to the
<code><a href="#idl-def-MIDIPort">MIDIPort</a></code> explicitly
unavailable (subsequently changing the state from "open" to "connected").
Note that successful invocation of this method will result in MIDI
messages no longer being delivered to MIDIMessageEvent handlers on a
<a>MIDIInputPort</a> (although setting a new handler will cause an
implicit open()).</p>
<p>The underlying implementation may not need to do anything in response
to this call. However, some underlying implementations may not be able
to support shared access to MIDI devices, and the explicit close() call
enables MIDI applications to ensure other applications can gain access
to devices.</p>
<p>When invoked, this method returns a Promise object representing a
request for access to the given MIDI port on the user's system.
When the port has been closed (and therefore, in exclusive access
systems, the port is available to other applications), the vended
Promise's <var>resolveCallback</var> is invoked with the
<code><a>MIDIPort</a></code> object as its argument. If the port is
disconnected, the Promise's <var>rejectCallback</var> (if any) is invoked.</p>
<p>When the <code>close()</code> method is called, the user
agent MUST run the <dfn>algorithm to close a MIDIPort</dfn>:</p>
<ol>
<li><p>Let <var>promise</var> be a new Promise object and
<var>resolver</var> be its associated resolver.</p></li>
<li><p>Return <var>promise</var> and run the following steps
asynchronously.</p></li>
<li><p>Let <var>port</var> be the given
<code><a href="#idl-def-MIDIPort">MIDIPort</a></code> object.</p></li>
<li><p>If the port is already closed (its <code><a
href="#widl-MIDIPort-connection">.connection</a></code> is <code><a
href="#idl-def-MIDIPortConnectionState.closed">"closed"</a></code>
- e.g. the port has not yet been implicitly or explictly opened,
or <code><a href="#widl-MIDIPort-close-Promise-MIDIPort">close()</a></code>
has already been called on this <code><a
href="#idl-def-MIDIPort">MIDIPort</a></code>), jump to the step
labeled <em><b>closed</b></em> below. </p></li>
<li><p>If the port is an input port, skip to the next step. If
the output port's <code><a href="#widl-MIDIPort-state">.state</a></code>
is not <code><a href="#idl-def-MIDIPortDeviceState.connected">"connected"</a></code>,
clear all pending send data and skip to the next step. Clear
any pending send data in the system with timestamps in the
future, then finish sending any send messages with no timestamp
or with a timestamp in the past or present, prior to proceeding
to the next step.</p></li>
<li><p>Close access to the port in the underlying system if open,
and release any blocking resources in the underlying system.</p></li>
<li><p>Change the <code>connection</code>
attribute of the MIDIPort to <code>"closed"</code>, and enqueue
a new <code><a>MIDIConnectionEvent</a></code> to the <code><a
href="#event-midiaccess-statechange">statechange</a></code>
handler of the <code><a>MIDIAccess</a></code> and to the
<code><a href="#event-midiport-statechange">statechange</a></code>
handler of the <code><a>MIDIPort</a></code>.</p>
<li><p><em><b>closed</b></em>: Call <var>resolver</var>'s
<code>accept(value)</code> method with
<var>port</var> as value argument.</p></li>
<li><p>Terminate these steps.</p></li>
</ol>
</dd>
</dl>
<p id="event-midiport-statechange">
Whenever the MIDI port corresponding to the
<code><a>MIDIPort</a></code> changes the state attribute, the user agent SHOULD
run the following steps:
</p>
<ol>
<li>
<p>
Let <code>port</code> be the <code><a>MIDIPort</a></code>.
</p>
</li>
<li>
<p>
Let <code>event</code> be a newly constructed
<code><a>MIDIConnectionEvent</a></code>, with the <code>port</code>
attribute set to the port.
</p>
</li>
<li>
<p>
Fire an event named <code><a
href="#event-midiport-statechange">statechange</a></code>
at the <a>MIDIPort</a>, and <code><a href="#event-midiaccess-statechange">statechange</a></code> at the <a>MIDIAccess</a>, using the <code>event</code> as the event object.
</p>
</li>
</ol>
<section>
<h3 id="MIDIInput"><a>MIDIInput</a> Interface</h3>
<dl title="interface MIDIInput : MIDIPort"
class="idl">
<dt>attribute <a>EventHandler</a> onmidimessage</dt>
<dd>
<p>
This <a>event handler</a>, of type <code><a href=
"#event-midiinput-message">MIDIMessage</a></code>,
MUST be supported by all objects implementing
<code><a>MIDIInput</a></code> interface.
</p>
<p>If the handler is set and the state attribute is not <code>"opened"</code>, underlying implementation tries to make the port available, and change the state attribute to <code>"opened"</code>. If succeeded, <code><a>MIDIConnectionEvent</a></code> is delived to the corresponding <code>MIDIPort</code> and <code>MIDIAccess</code>.
</dd>
</dl>
<p id="event-midiinput-message">
Whenever the MIDI port corresponding to the
<code><a>MIDIInput</a></code> finishes receiving one or more MIDI messages, the user agent MUST
run the following steps:
</p>
<ol>
<li>
<p>
Let <code>port</code> be the <code><a>MIDIInput</a></code>.
</p>
</li>
<li>
<p>
If the <code><a>MIDIAccess</a></code> did not enable system exclusive access, and the message is a system exclusive message, abort this process.
</p>
</li>
<li>
<p>
Let <code>event</code> be a newly constructed
<code><a>MIDIMessageEvent</a></code>, with the <code>timestamp</code>
attribute set to the time the message was received by the system, and
with the <code>data</code> attribute set to a Uint8Array of MIDI data
bytes representing a single MIDI message.
</p>
</li>
<li>
<p>
Fire an event named <code><a
href="#event-midiinput-message">midimessage</a></code>
at the <code>port</code>, using the <code>event</code> as the event object.
</p>
</li>
</ol>
<p>It is specifically noted that MIDI System Real-Time Messages may actually occur in the middle of other messages in the input stream; in this case, the System Real-Time messages will be dispatched as they occur, while the normal messages will be buffered until they are complete (and then dispatched).
</p>
</section>
<section>
<h3 id="MIDIOutput"><a>MIDIOutput</a> Interface</h3>
<dl title="interface MIDIOutput : MIDIPort"
class="idl">
<dt>void send( sequence<octet> data, optional double timestamp )</dt>
<dd>
<p>
Enqueues the message to be sent to the corresponding MIDI port. The underlying implementation will (if necessary) coerce each member of the sequence to an unsigned 8-bit integer. The use of sequence rather than a Uint8Array enables developers to use the convenience of <code>output.send( [ 0x90, 0x45, 0x7f ] );</code> rather than having to create a Uint8Array, e.g. <code>output.send( new Uint8Array( [ 0x90, 0x45, 0x7f ] ) );</code> - while still enabling use of Uint8Arrays for efficiency in large MIDI data scenarios (e.g. reading Standard MIDI Files and sending sysex messages).
</p>
<p>
The data contains one or more valid, complete MIDI messages. Running status is not allowed in the data, as underlying systems may not support it.
</p>
<p>
If <var>data</var> is not a valid sequence or does not contain a valid MIDI message, throw a <code>TypeError</code> exception.
</p>
<p>
If <var>data</var> is a system exclusive message, and the <code><a>MIDIAccess</a></code> did not enable system exclusive access, throw an <code>InvalidAccessError</code> exception.
</p>
<p>
If the port is <code><a
href="#idl-def-MIDIPortDeviceState.disconnected">"disconnected"</a></code>,
throw an <code>InvalidStateError</code> exception.
</p>
<p>
If the port is <code><a
href="#idl-def-MIDIPortDeviceState.connected">"connected"</a></code>
but the connection is <code><a
href="#idl-def-MIDIPortConnectionState.closed">"closed"</a></code>,
asynchronously try to <a href="#midiport-open-algorithm">open the port</a>.
</p>
<dl class='parameters'>
<dt>sequence<octet> data</dt>
<dd>
The data to be enqueued, with each sequence entry representing a single byte of data.
</dd>
<dt>optional double timestamp</dt>
<dd>
The time at which to begin sending the data to the port (as a <a href="#DomHighResTimeStampDfn">DOMHighResTimeStamp</a> - a number of milliseconds measured relative to the navigation start of the document). If <code>timestamp</code> is not present or is set to zero (or another time in the past), the data is to be sent as soon as possible.
</dd>
</dl>
</dd>
<dt>void clear()</dt>
<dd>
<p>Clears any pending send data that has not yet been sent from the <code>MIDIOutput</code>'s queue. The implementation will need to ensure the MIDI stream is left in a good state, so if the output port is in the middle of a sysex message, a sysex termination byte (0xf7) should be sent.</p>
</dd>
</dl>
</section>
</section>
<section>
<h2 id="MIDIMessageEvent"><a>MIDIMessageEvent</a> Interface</h2>
<p>An event object implementing this interface is passed to a MIDIInput's onmidimessage handler when MIDI messages are received.</p>
<dl title="[Constructor(DOMString type, optional MIDIMessageEventInit eventInitDict)] interface MIDIMessageEvent : Event"
class="idl">
<dt>readonly attribute double receivedTime</dt>
<dd>
<p>A <code>DOMHighResTimeStamp</code> specifying when the event occurred.</p>
<p class="note">The DOM4 <a class="externalDFN">Event</a> object has a timeStamp member in the event object that will be filled out with the current time, but that it is lower precision (DOMTimeStamp is defined as an integer number of milliseconds), has a different zero reference (DOMTimeSTamp is the number of milliseconds that has passed since 00:00:00 UTC on 1 January 1970), and therefore is less suitable for MIDI applications.</p>
</dd>
<dt>readonly attribute Uint8Array data</dt>
<dd>
<p>A Uint8Array containing the MIDI data bytes of a single MIDI message.</p>
</dd>
</dl>
<section>
<h2 id="MIDIMessageEventInit"><a>MIDIMessageEventInit</a> Interface</h2>
<dl title="dictionary MIDIMessageEventInit : EventInit"
class="idl">
<dt>double receivedTime</dt>
<dd>
<p>A <code>DOMHighResTimeStamp</code> specifying when the event occurred.</p>
</dd>
<dt>Uint8Array data</dt>
<dd>
<p>A Uint8Array containing the MIDI data bytes of a single MIDI message.</p>
</dd>
</dl>
</section>
</section>
<section>
<h2 id="MIDIConnectionEvent"><a>MIDIConnectionEvent</a> Interface</h2>
<p>An event object implementing this interface is passed to a
MIDIAccess' onstatechange handler when a new port becomes available
(for example, when a MIDI device is first plugged in to the computer),
when a previously-available port becomes unavailable, or becomes
available again (for example, when a MIDI interface is disconnected,
then reconnected) and (if present) is also passed to the onstatechange
handlers for any <code><a href="#idl-def-MIDIPort">MIDIPort</a></code>s
referencing the port.</p>
<p>When a <code><a href="#idl-def-MIDIPort">MIDIPort</a></code> is in
the <code><a
href="#idl-def-MIDIPortConnectionState.pending">"pending"</a></code>
state and the device is reconnected to the host system, prior to
firing a <code><a href="#event-midiaccess-statechange">statechange</a></code>
event the <a href="#midiport-open-algorithm">MIDIPort open
algorithm</a> is run on it to attempt to reopen the port. If this
transition fails (e.g. the Port is reserved by something else in the
underlying system, and therefore unavailable for use), the connection
state moves to "closed", else it transitions back to "open". This is
done prior to the <code><a
href="#event-midiaccess-statechange">statechange</a></code> event for
the device state change so that the event will reflect the final
connection state as well as the device state.</p>
<p>Some underlying systems may not provide notification events for device
connection status; such systems may have long time delays as they poll
for new devices infrequently. As such, it is suggested that heavy
reliance on connection events not be used.</p>
<dl title="[Constructor(DOMString type, optional MIDIConnectionEventInit eventInitDict)] interface MIDIConnectionEvent : Event"
class="idl">
<dt>readonly attribute MIDIPort port</dt>
<dd>
<p>The port that has been connected or disconnected.</p>
</dd>
</dl>
<section>
<h2 id="MIDIConnectionEventInit"><a>MIDIConnectionEventInit</a> Interface</h2>
<dl title="dictionary MIDIConnectionEventInit : EventInit"
class="idl">
<dt>MIDIPort port</dt>
<dd>
<p>The port that has been connected or disconnected.</p>
</dd>
</dl>
</section>
</section>
<section class="informative">
<h2 id="examples">Examples of Web MIDI API Usage in JavaScript</h2>
<p>The following are some examples of common MIDI usage in JavaScript.</p>
<section>
<h3>Getting Access to the MIDI System</h3>
<p>This example shows how to request access to the MIDI system.</p>
<pre class="code es-code">var midi = null; // global MIDIAccess object
function onMIDISuccess( midiAccess ) {
console.log( "MIDI ready!" );
midi = midiAccess; // store in the global (in real usage, would probably keep in an object instance)
}
function onMIDIFailure(msg) {
console.log( "Failed to get MIDI access - " + msg );
}
navigator.requestMIDIAccess().then( onMIDISuccess, onMIDIFailure );</pre>
</section>
<section>
<h3>Requesting Access to the MIDI System with System Exclusive Support</h3>
<p>This example shows how to request access to the MIDI system, including the ability to send and receive system exclusive messages.</p>
<pre class="code es-code">var midi = null; // global MIDIAccess object
function onMIDISuccess( midiAccess ) {
console.log( "MIDI ready!" );
midi = midiAccess; // store in the global (in real usage, would probably keep in an object instance)
}
function onMIDIFailure(msg) {
console.log( "Failed to get MIDI access - " + msg );
}
navigator.requestMIDIAccess( { sysex: true } ).then( onMIDISuccess, onMIDIFailure );</pre>
</section>
<section>
<h3>Listing Inputs and Outputs</h3>
<p>This example gets the list of the input and output ports and prints their information to the console log, using ES6 for...of notation.
<pre class="code es-code">function listInputsAndOutputs( midiAccess ) {
for (var entry of midiAccess.inputs) {
var input = entry[1];
console.log( "Input port [type:'" + input.type + "'] id:'" + input.id +
"' manufacturer:'" + input.manufacturer + "' name:'" + input.name +
"' version:'" + input.version + "'" );
}
for (var entry of midiAccess.outputs) {
var output = entry[1];
console.log( "Output port [type:'" + output.type + "'] id:'" + output.id +
"' manufacturer:'" + output.manufacturer + "' name:'" + output.name +
"' version:'" + output.version + "'" );
}
}</pre>
</section>
<section>
<h3>Handling MIDI Input</h3>
<p>This example prints incoming MIDI messages on a single arbitrary input port to the console log.</p>
<pre class="code es-code">function onMIDIMessage( event ) {
var str = "MIDI message received at timestamp " + event.timestamp + "[" + event.data.length + " bytes]: ";
for (var i=0; i<event.data.length; i++) {
str += "0x" + event.data[i].toString(16) + " ";
}
console.log( str );
}
function startLoggingMIDIInput( midiAccess, indexOfPort ) {
midiAccess.inputs.forEach( function(entry) {entry.onmidimessage = onMIDIMessage;});
}</pre>
</section>
<section>
<h3>Sending MIDI Messages to an Output Device</h3>
<p>This example sends a middle C note on message immediately on MIDI channel 1 (MIDI channels are 0-indexed, but generally referred to as channels 1-16), and queues a corresponding note off message for 1 second later.</p>
<pre class="code es-code">function sendMiddleC( midiAccess, portID ) {
var noteOnMessage = [0x90, 60, 0x7f]; // note on, middle C, full velocity
var output = midiAccess.outputs.get(portID);
output.send( noteOnMessage ); //omitting the timestamp means send immediately.
output.send( [0x80, 60, 0x40], window.performance.now() + 1000.0 ); // Inlined array creation- note off, middle C,
// release velocity = 64, timestamp = now + 1000ms.
}</pre>
</section>
<section>
<h3>A Simple Loopback</h3>
<p>This example loops all input messages on the first input port to the first output port - including system exclusive messages.</p>
<pre class="code es-code">var midi = null; // global MIDIAccess object
var output = null;
function echoMIDIMessage( event ) {
if (output) {
output.send( event.data, event.timestamp );
}
}
function onMIDISuccess( midiAccess ) {
console.log( "MIDI ready!" );
var input = midiAccess.inputs.entries.next();
if (input)
input.onmidimessage = echoMIDIMessage;
output = midiAccess.outputs.values().next().value;
if (!input || !output)
console.log("Uh oh! Couldn't get i/o ports.");
}
function onMIDIFailure(msg) {
console.log( "Failed to get MIDI access - " + msg );
}
navigator.requestMIDIAccess().then( onMIDISuccess, onMIDIFailure );</pre>
</section>
<section>
<h3>A Simple Monophonic Sine Wave MIDI Synthesizer</h3>
<p>This example listens to all input messages from all available input ports, and uses note messages to drive the envelope and frequency on a monophonic sine wave oscillator, creating a very simple synthesizer, using the <a>Web Audio API</a>. Note on and note off messages are supported, but sustain pedal, velocity and pitch bend are not. This sample is also hosted on <a href="http://webaudiodemos.appspot.com/monosynth/index.html">webaudiodemos.appspot.com</a>.</p>
<pre class="code es-code">var context=null; // the Web Audio "context" object
var midiAccess=null; // the MIDIAccess object.
var oscillator=null; // the single oscillator
var envelope=null; // the envelope for the single oscillator
var attack=0.05; // attack speed
var release=0.05; // release speed
var portamento=0.05; // portamento/glide speed
var activeNotes = []; // the stack of actively-pressed keys
window.addEventListener('load', function() {
// patch up prefixes
window.AudioContext=window.AudioContext||window.webkitAudioContext;