1

I have created a simple script to list connected midi input devices. This works fine in Chrome on Windows but fails on Chrome on Mac with 'Cannot read property name of undefined'. This also happens if I copy and paste the code from the w3c.org example:http://www.w3.org/TR/webmidi/#listing-inputs-and-outputs

Here's my code:

var midiTest = {
  midiAcess: null,
  init: function() {
    function onMIDISuccess(midiAccess) {
      console.log(midiAccess);
      var inputDeviceCount = midiAccess.inputs.size;
      if(inputDeviceCount > 0) {
        for(var i=0; i<inputDeviceCount; i++) {
          var input = midiAccess.inputs.get(i);
          var deviceName = input.name;
          console.log(deviceName);
        }
      }
    }
    function onMIDIFailure(e) {
      console.log('No access to MIDI devices' + e);
    }
    if(navigator.requestMIDIAccess)
      navigator.requestMIDIAccess({ sysex: false }).then(onMIDISuccess, onMIDIFailure);
    else
      alert("No MIDI support in your browser.");
  },
};

midiTest.init();

console.log(midiAccess) works fine. Any idea what's going on here?

thanksd
  • 54,176
  • 22
  • 157
  • 150
ezero
  • 1,230
  • 3
  • 12
  • 27

3 Answers3

3

Got it working now by swapping out the loop for this:

var inputs=midiAccess.inputs.values();

for ( var input = inputs.next(); input && !input.done; input = inputs.next()) {
    var deviceName = input.value.name;
    console.log(deviceName);
}

This works on mac and windows, no idea why the previous code did not work.

ezero
  • 1,230
  • 3
  • 12
  • 27
2

I may be a bit late, but midiAccess.inputs has a forEach method :

midiAccess.inputs.forEach(function (input) {
    console.log(input.name);
});
Mel Ferrer
  • 56
  • 5
0

To provide a little more clarification as to why the midiTest code worked on Windows and not on macOS.

The get method on midiAccess.inputs expects a port ID. Windows doesn't support "completely unique persistent identifiers" and instead uses just an index of the connected MIDI device or USB port. On macOS, which does support "completely unique persistent identifiers", these ids are a string of unique numbers. So, trying to get a port using a port index wouldn't return any devices on macOS.

https://webaudio.github.io/web-midi-api/#dom-midiport-id

Andrej
  • 61
  • 5