Copyright © 2015 W3C® (MIT, ERCIM, Keio, Beihang). W3C liability, trademark and document use rules apply.
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.
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).
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 <audio>
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.
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.
This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.
This document was published by the Audio Working Group as a Working Draft. This document is intended to become a W3C Recommendation. If you wish to make comments regarding this document, please send them to public-audio@w3.org (subscribe, archives). All comments are welcome.
Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.
This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.
This document is governed by the 1 August 2014 W3C Process Document.
This section is non-normative.
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.
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.
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).
As well as sections marked as non-normative, all authoring guidelines, diagrams, examples, and notes in this specification are non-normative. Everything else in this specification is normative.
The key words MUST and SHOULD are to be interpreted as described in [RFC2119].
This specification defines conformance criteria that apply to a single product: the user agent that implements the interfaces that it contains.
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.
The concepts queue a task and fires a simple event are defined in [HTML5].
The terms
event handlers and
event handler event types and corresponding EventHandler
interface are defined in [HTML5].
The Uint8Array interface is defined in [TYPED-ARRAYS].
The term octet is defined in [WEBIDL].
The Web Audio API and its associated interfaces and concepts are defined in [webaudio].
The Event interface is defined in [DOM4].
The DOMError interface is defined in [DOM-LEVEL-3-CORE].
The DOMHighResTimeStamp interface is defined in [HIGHRES-TIME].
The terms MIDI, MIDI device, MIDI input port, MIDI output port, MIDI interface, MIDI message, MIDI System Real-Time message and system exclusive are defined in [MIDI].
The Promise interface is currently defined in the WHATWG DOM specification.
When invoked, returns a Promise object representing a request for access to MIDI devices on the user's system.
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 resolveCallback is invoked, as a
(i.e., with a
MIDISuccessCallback
object and a MIDIAccess
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.MIDIOptions
If the user declines or the call is denied for any other reason, the Promise's
rejectCallback (if any) is invoked with a DOMException
parameter.
When the
requestMIDIAccess
method is called, the user
agent MUST run the algorithm to request MIDI Access:
Let promise be a new Promise object and resolver be its associated resolver.
Return promise and run the following steps asynchronously.
Optionally, e.g. based on a previously-established user preference, for security reasons, or due to platform limitations, jump to the step labeled failure below.
Optionally, e.g. based on a previously-established user preference, jump to the step labeled success below.
Prompt the user in a user-agent-specific manner for
permission to provide the entry script's origin with a
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.
MIDIAccess
If permission is denied, jump to the step labeled failure below. If the user never responds, this algorithm will never progress beyond this step. If permission is granted, continue the following steps.
success: Let access be a new
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.)MIDIAccess
Call resolver's accept(value)
method with access as value argument.
Terminate these steps.
failure: Let error be a new DOMException
.
This exception's .name should be "SecurityError"
if the
user or their security settings denied the application from creating a MIDIAccess instance with the requested options, "AbortError"
if the page is going to be closed for a user navigation, "InvalidStateError"
if the underlying systems raise any errors, or otherwise it should be "NotSupportedError"
.
Call resolver's reject(value)
method with error as value argument.
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
options |
| ✘ | ✔ |
Promise<MIDIAccess
>
MIDIOptions
dictionaryThis dictionary contains optional settings that may be provided to the requestMIDIAccess request.
dictionary MIDIOptions {
boolean sysex;
};
MIDIOptions
Memberssysex
of type booleanThis member informs the system whether the ability to send and receive system exclusive messages is requested or allowed on a given MIDIAccess
object. On the option passed to requestMIDIAccess
, 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 "SecurityError"
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.
In the options
parameter passed to the resolveCallback, this member indicates whether system exclusive is allowed on the MIDIAccess.
MIDIInputMap
Interfaceinterface MIDIInputMap {
readonly maplike<DOMString, MIDIInput
>;
};
This is a maplike interface whose value is a MIDIInput instance and key is its ID.
This type is used to represent all the currently available MIDI input ports. This enables
// 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); }
MIDIOutputMap
Interfaceinterface MIDIOutputMap {
readonly maplike<DOMString, MIDIOutput
>;
};
This is a maplike interface whose value is a MIDIOutput instance and key is its ID.
This type is used to represent all the currently available MIDI output ports. This enables
// 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 = input.name; document.getElementById("inputportselector").add(opt); }
MIDISuccessCallback
callback MIDISuccessCallback = void (MIDIAccess
access, MIDIOptions
options);
MIDISuccessCallback
Parametersaccess
of type MIDIAccess
A
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.
MIDIAccess
Note: 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.
options
of type MIDIOptions
This parameter describes the options enabled on this MIDIAccess
object.
MIDIAccess
InterfaceThis interface provides the methods to list MIDI input and output devices, and obtain access to an individual device.
interface MIDIAccess : EventTarget {
readonly attribute MIDIInputMap
inputs;
readonly attribute MIDIOutputMap
outputs;
attribute EventHandler onstatechange;
readonly attribute boolean sysexEnabled;
};
inputs
of type MIDIInputMap
, readonly onstatechange
of type EventHandler, The handler called when a new port is connected or an existing port changes the state attribute.
This event handler, of type MIDIConnectionEvent
,
MUST be supported by all objects implementing the
interface.
MIDIAccess
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:
port
be the MIDIPort
corresponding to the newly-available, or the existing port.event
be a newly constructed MIDIConnectionEvent
, with the port
attribute set to the port.statechange
at the MIDIAccess
, using the event
as the event object.outputs
of type MIDIOutputMap
, readonly sysexEnabled
of type boolean, readonly MIDIPort
InterfaceThis interface represents a MIDI input or output port.
enum MIDIPortType {
"input",
"output"
};
Enumeration description | |
---|---|
input | If a MIDIPort is an input port, the type member MUST be this value. |
output | If a MIDIPort is an output port, the type member MUST be this value. |
enum MIDIPortDeviceState {
"disconnected",
"connected"
};
Enumeration description | |
---|---|
disconnected | 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. |
connected | The device that MIDIPort represents is connected, and should appear in the map of input and output ports. |
enum MIDIPortConnectionState {
"open",
"closed",
"pending"
};
Enumeration description | |
---|---|
open | The device that MIDIPort represents has been opened (either implicitly or explicitly) and is available for use. |
closed |
The device that MIDIPort represents has not been opened, or has been explicitly closed. Until a MIDIPort has been opened either explicitly (through open() ) or implicitly (by adding a midimessage event handler on an input port, or calling send() on an output port, this should be the default state of the device.
|
pending |
The device that MIDIPort represents has been opened (either implicitly or explicitly), but the device has subsequently been disconnected and is unavailable for use. If the device is reconnected, prior to sending a statechange event, the system should attempt to reopen the device (following the algorithm to open a MIDIPort); this will result in either the connection state transitioning to "open" or to "closed".
|
interface MIDIPort : EventTarget {
readonly attribute DOMString id;
readonly attribute DOMString? manufacturer;
readonly attribute DOMString? name;
readonly attribute MIDIPortType
type;
readonly attribute DOMString? version;
readonly attribute MIDIPortDeviceState
state;
readonly attribute MIDIPortConnectionState
connection;
attribute EventHandler onstatechange;
Promise<MIDIPort
> open ();
Promise<MIDIPort
> close ();
};
connection
of type MIDIPortConnectionState
, readonly id
of type DOMString, readonly
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 id
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.
manufacturer
of type DOMString, readonly , nullableThe manufacturer of the port.
name
of type DOMString, readonly , nullableThe system name of the port.
onstatechange
of type EventHandler, The handler called when an existing port changes its state or connection attributes.
This event handler, of type statechange
,
MUST be supported by all objects implementing
interface.
MIDIPort
state
of type MIDIPortDeviceState
, readonly type
of type MIDIPortType
, readonly
A descriptor property to distinguish whether the port is an
input or an output port.
For
,
this MUST be MIDIOutput
"output"
.
For
,
this MUST be MIDIInput
"input"
.
version
of type DOMString, readonly , nullableThe version of the port.
close
Makes the MIDI device corresponding to the
MIDIPort
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
MIDIInputPort (although setting a new handler 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, and the explicit close() call enables MIDI applications to ensure other applications can gain access to devices.
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 resolveCallback is invoked with the
object as its argument. If the port is
disconnected, the Promise's rejectCallback (if any) is invoked.MIDIPort
When the close()
method is called, the user
agent MUST run the algorithm to close a MIDIPort:
Let promise be a new Promise object and resolver be its associated resolver.
Return promise and run the following steps asynchronously.
Let port be the given
MIDIPort
object.
If the port is already closed (its .connection
is "closed"
- e.g. the port has not yet been implicitly or explictly opened,
or close()
has already been called on this MIDIPort
), jump to the step
labeled closed below.
If the port is an input port, skip to the next step. If
the output port's .state
is not "connected"
,
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.
Close access to the port in the underlying system if open, and release any blocking resources in the underlying system.
success: Change the connection
attribute of the MIDIPort to "closed"
, and enqueue
a new
to the MIDIConnectionEvent
statechange
handler of the
and to the
MIDIAccess
statechange
handler of the
.MIDIPort
closed: Call resolver's
accept(value)
method with
port as value argument.
Terminate these steps.
failure: Let error be a new
DOMException
. This exception's .name should be
"InvalidStateError"
if the port is disconnected.
Call resolver's reject(value)
method
with error as value argument.
Promise<MIDIPort
>
open
Makes the MIDI device corresponding to the MIDIPort
explicitly
available. Note that this call is NOT required in order to use the
MIDIPort
- calling send()
on a MIDIOutput
or attaching a MIDIMessageEvent handler on a MIDIInputPort 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.
When invoked, this method returns a Promise object representing a request for access to the given MIDI port on the user's system.
If the port device has a state of
"connected"
,
when access to the port has been obtained (and the port is ready for
input or output), the vended Promise's resolveCallback is
invoked with a
object as its argument.
MIDIPort
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 rejectCallback (if any) is invoked.
If open()
is called on a port that is
"disconnected"
,
the port's .connection
will transition to
"pending"
,
until the port becomes "connected"
or all references to it are dropped.
When this method is called, the user agent MUST run the algorithm to open a MIDIPort:
Let promise be a new Promise object and resolver be its associated resolver.
Return promise and run the following steps asynchronously.
Let port be the given
MIDIPort
object.
If the device's state is already "open"
(e.g. open() has already been called on this MIDIPort, or the
port has been implicitly opened), jump to the step labeled
opened below.
If the device's state is "pending"
(i.e. the connection had been opened and the device was
subsequently disconnected), jump to the step labeled
opened below.
If the device's state is "disconnected"
,
change the state
attribute of the
MIDIPort
to
"pending"
,
and enqueue a new MIDIConnectionEvent
to the statechange
handler of the
and to the
MIDIAccess
statechange
handler of the MIDIPort
and jump to the step labeled opened below.
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 failure below. If the device available and access is obtained, continue the following steps.
success: Change the state
attribute of the MIDIPort to
"opened"
, and enqueue a new
to the MIDIConnectionEvent
statechange
handler of the
and to the
MIDIAccess
statechange
handler of the MIDIPort
.
If this port is an output port and has any pending data that is waiting to be sent, asynchronously begin sending that data.
opened: Call resolver's
accept(value)
method with port as
value argument.
Terminate these steps.
failure: Let error be a new
DOMException
. This exception's .name should be
"InvalidAccessError"
if the port is unavailable,
or "InvalidStateError"
if the port is disconnected.
Call resolver's reject(value)
method
with error as value argument.
Promise<MIDIPort
>
Whenever the MIDI port corresponding to the
changes the state attribute, the user agent SHOULD
run the following steps:
MIDIPort
Let port
be the
.
MIDIPort
Let event
be a newly constructed
, with the MIDIConnectionEvent
port
attribute set to the port.
Fire an event named statechange
at the MIDIPort
, and statechange
at the MIDIAccess
, using the event
as the event object.
MIDIInput
Interfaceinterface MIDIInput : MIDIPort
{
attribute EventHandler onmidimessage;
};
onmidimessage
of type EventHandler,
This event handler, of type MIDIMessage
,
MUST be supported by all objects implementing
interface.
MIDIInput
If the handler is set and the state attribute is not "opened"
, underlying implementation tries to make the port available, and change the state attribute to "opened"
. If succeeded,
is delived to the corresponding MIDIConnectionEvent
MIDIPort
and MIDIAccess
.
Whenever the MIDI port corresponding to the
finishes receiving one or more MIDI messages, the user agent MUST
run the following steps:
MIDIInput
Let port
be the
.
MIDIInput
If the
did not enable system exclusive access, and the message is a system exclusive message, abort this process.
MIDIAccess
Let event
be a newly constructed
, with the MIDIMessageEvent
timestamp
attribute set to the time the message was received by the system, and
with the data
attribute set to a Uint8Array of MIDI data
bytes representing a single MIDI message.
Fire an event named midimessage
at the port
, using the event
as the event object.
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).
MIDIOutput
Interfaceinterface MIDIOutput : MIDIPort
{
void send (sequence<octet> data, optional double timestamp);
void clear ();
};
clear
Clears any pending send data that has not yet been sent from the MIDIOutput
'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.
void
send
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 output.send( [ 0x90, 0x45, 0x7f ] );
rather than having to create a Uint8Array, e.g. output.send( new Uint8Array( [ 0x90, 0x45, 0x7f ] ) );
- while still enabling use of Uint8Arrays for efficiency in large MIDI data scenarios (e.g. reading Standard MIDI Files and sending sysex messages).
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.
If data is not a valid sequence or does not contain a valid MIDI message, throw a TypeError
exception.
If data is a system exclusive message, and the
did not enable system exclusive access, throw an MIDIAccess
InvalidAccessError
exception.
If the port is "disconnected"
,
throw an InvalidStateError
exception.
If the port is "connected"
but the connection is "closed"
,
asynchronously try to open the port.
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
data | sequence<octet> | ✘ | ✘ | The data to be enqueued, with each sequence entry representing a single byte of data. |
timestamp | double | ✘ | ✔ |
The time at which to begin sending the data to the port (as a DOMHighResTimeStamp - a number of milliseconds measured relative to the navigation start of the document). If timestamp is not present or is set to zero (or another time in the past), the data is to be sent as soon as possible.
|
void
MIDIMessageEvent
InterfaceAn event object implementing this interface is passed to a MIDIInput's onmidimessage handler when MIDI messages are received.
[Constructor(DOMString type, optional MIDIMessageEventInit eventInitDict)]
interface MIDIMessageEvent : Event {
readonly attribute double receivedTime;
readonly attribute Uint8Array data;
};
data
of type Uint8Array, readonly A Uint8Array containing the MIDI data bytes of a single MIDI message.
receivedTime
of type double, readonly A DOMHighResTimeStamp
specifying when the event occurred.
The DOM4 Event 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.
MIDIMessageEventInit
Interfacedictionary MIDIMessageEventInit : EventInit {
double receivedTime;
Uint8Array data;
};
MIDIMessageEventInit
Membersdata
of type Uint8ArrayA Uint8Array containing the MIDI data bytes of a single MIDI message.
receivedTime
of type doubleA DOMHighResTimeStamp
specifying when the event occurred.
MIDIConnectionEvent
InterfaceAn 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 MIDIPort
s
referencing the port.
When a MIDIPort
is in
the "pending"
state and the device is reconnected to the host system, prior to
firing a statechange
event the MIDIPort open
algorithm 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 statechange
event for
the device state change so that the event will reflect the final
connection state as well as the device state.
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.
[Constructor(DOMString type, optional MIDIConnectionEventInit eventInitDict)]
interface MIDIConnectionEvent : Event {
readonly attribute MIDIPort
port;
};
port
of type MIDIPort
, readonly The port that has been connected or disconnected.
MIDIConnectionEventInit
Interfacedictionary MIDIConnectionEventInit : EventInit {
MIDIPort
port;
};
MIDIConnectionEventInit
Membersport
of type MIDIPort
The port that has been connected or disconnected.
This section is non-normative.
The following are some examples of common MIDI usage in JavaScript.
This example shows how to request access to the MIDI system.
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 );
This example shows how to request access to the MIDI system, including the ability to send and receive system exclusive messages.
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 );
This example gets the list of the input and output ports and prints their information to the console log, using ES6 for...of notation.
function listInputsAndOutputs( midiAccess ) { for (var input in midiAccess.inputs) { console.log( "Input port [type:'" + input.type + "'] id:'" + input.id + "' manufacturer:'" + input.manufacturer + "' name:'" + input.name + "' version:'" + input.version + "'" ); } for (var output in midiAccess.outputs) { console.log( "Output port [type:'" + output.type + "'] id:'" + output.id + "' manufacturer:'" + output.manufacturer + "' name:'" + output.name + "' version:'" + output.version + "'" ); } }
This example prints incoming MIDI messages on a single arbitrary input port to the console log.
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.value.onmidimessage = onMIDIMessage;}); }
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.
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. }
This example loops all input messages on the first input port to the first output port - including system exclusive messages.
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 );
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 Web Audio API. Note on and note off messages are supported, but sustain pedal, velocity and pitch bend are not. This sample is also hosted on webaudiodemos.appspot.com.
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; context = new AudioContext(); if (navigator.requestMIDIAccess) navigator.requestMIDIAccess().then( onMIDIInit, onMIDIReject ); else alert("No MIDI support present in your browser. You're gonna have a bad time.") // set up the basic oscillator chain, muted to begin with. oscillator = context.createOscillator(); oscillator.frequency.setValueAtTime(110, 0); envelope = context.createGain(); oscillator.connect(envelope); envelope.connect(context.destination); envelope.gain.value = 0.0; // Mute the sound oscillator.start(0); // Go ahead and start up the oscillator } ); function onMIDIInit(midi) { midiAccess = midi; var haveAtLeastOneDevice=false; var inputs=midiAccess.inputs.values(); for ( var input = inputs.next(); input && !input.done; input = inputs.next()) { input.value.onmidimessage = MIDIMessageEventHandler; haveAtLeastOneDevice = true; } if (!haveAtLeastOneDevice) alert("No MIDI input devices present. You're gonna have a bad time."); } function onMIDIReject(err) { alert("The MIDI system failed to start. You're gonna have a bad time."); } function MIDIMessageEventHandler(event) { // Mask off the lower nibble (MIDI channel, which we don't care about) switch (event.data[0] & 0xf0) { case 0x90: if (event.data[2]!=0) { // if velocity != 0, this is a note-on message noteOn(event.data[1]); return; } // if velocity == 0, fall thru: it's a note-off. MIDI's weird, y'all. case 0x80: noteOff(event.data[1]); return; } } function frequencyFromNoteNumber( note ) { return 440 * Math.pow(2,(note-69)/12); } function noteOn(noteNumber) { activeNotes.push( noteNumber ); oscillator.frequency.cancelScheduledValues(0); oscillator.frequency.setTargetAtTime( frequencyFromNoteNumber(noteNumber), 0, portamento ); envelope.gain.cancelScheduledValues(0); envelope.gain.setTargetAtTime(1.0, 0, attack); } function noteOff(noteNumber) { var position = activeNotes.indexOf(noteNumber); if (position!=-1) { activeNotes.splice(position,1); } if (activeNotes.length==0) { // shut off the envelope envelope.gain.cancelScheduledValues(0); envelope.gain.setTargetAtTime(0.0, 0, release ); } else { oscillator.frequency.cancelScheduledValues(0); oscillator.frequency.setTargetAtTime( frequencyFromNoteNumber(activeNotes[activeNotes.length-1]), 0, portamento ); } }
There are two primary security and privacy concerns with adding the Web MIDI API to the web platform:
Few systems will have significant numbers of MIDI devices attached; those systems that do will typically use hardware MIDI interfaces, not fanning out a dozen USB-MIDI connections through USB hubs. In this case, of course, enumerating the MIDI “devices” will only see the hardware MIDI interface(s), not the synthesizers, samplers, etc. plugged into it on the other side. Given the few number of devices plugged in, the amount of information exposed here is fairly symmetric with the fingerprinting concern exposed by other APIs such as the Gamepad API. The vast majority of systems have relatively few MIDI interfaces attached.
In brief, the general categories of things you can do with MIDI ports are:
The impact of each of these is:
It's also useful to examine what scenarios are enabled by MIDI, mapped against these features:
In short: the additional fingerprinting exposure of enumerating MIDI devices is directly analogous to the Gamepad API’s additional fingerprinting exposure through gamepad enumeration; typical users will only have at most a few devices connected, their configuration may change, and the information exposed is about the interface itself (i.e., no user-configured data).
The additional security concern for receiving short messages is also small - it’s analogous to listening to keyboard, mouse, mobile/laptop accelerometer, touch input or gamepad events; there is no additional information exposed, and all messages other than clock signals must be initiated by the user.
The additional concerns about sending short messages are analogous to any audio output - you cannot overwrite user information or expose use information, but you can make sounds happen, change patches, or (in rare configurations) toggle lights - but non-destructively, and not persistently.
System Exclusive, on the other hand, has a much less bounded potential, and it seems that distinguishing requests for SysEx separately in the API is a good idea, in order to more carefully provide user security hooks. The suggested security model explicitly allows user agents to require the user's approval before giving access to MIDI devices, although it is not currently required to prompt the user for this approval - but it also detailed that system exclusive support must be requested as part of that request.