Search code examples
javascriptweb-midi

WebMidi.js outputs is empty


I am trying to use WebMidi.js to play a note in the browser. I am using the code below which is mostly taken from the quick start guide.

<body>
  <script src="node_modules/webmidi/webmidi.min.js"></script>
  <script defer>
    WebMidi.enable(function(err) {
      if (err) {
        console.log("WebMidi could not be enabled.", err);
      } else {
        console.log("WebMidi enabled!");
        console.log("outputs:", WebMidi.outputs);
      }
    });
  </script>
</body>

When I load the page, it says that WebMidi is enabled but the outputs array is empty. How can I get the package to detect my outputs? I am using Chrome on Mac -- my software is up-to-date.


Solution

  • To use MIDI outputs to play a sound you would need to have a hardware or a software MIDI synthesizer with virtual MIDI ports running. You probably want to use AudioContext instead:

    // 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
    

    For generating more sophisticated sounds check out SoundJS or another sound library.