Skip to content
This repository was archived by the owner on Aug 23, 2025. It is now read-only.

Commit c3ba30f

Browse files
committed
allow passing custom navigator to MIDI
1 parent 1690f1a commit c3ba30f

File tree

1 file changed

+10
-27
lines changed

1 file changed

+10
-27
lines changed

packages/core/src/midi.js

Lines changed: 10 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -36,65 +36,48 @@ export class Eventable {
3636
}
3737

3838
export class MIDI extends Eventable {
39-
constructor() {
39+
constructor(_navigator = navigator) {
4040
super();
4141

4242
this.midiAccess = null;
4343

4444
// Try to get MIDI access
45-
this.getMIDIAccess();
45+
this.getMIDIAccess(_navigator);
4646
}
4747

4848
// Try to get MIDI access from the browser
49-
async getMIDIAccess() {
49+
async getMIDIAccess(_navigator) {
5050
// If MIDI is not supported by this browser
51-
if (!("requestMIDIAccess" in navigator)) return;
51+
if (!("requestMIDIAccess" in _navigator)) return;
5252

53-
this.midiAccess = await navigator.requestMIDIAccess({ sysex: false });
53+
this.midiAccess = await _navigator.requestMIDIAccess({ sysex: false });
5454

5555
console.log("got MIDI access");
5656

5757
// For each MIDI input
5858
for (let input of this.midiAccess.inputs.values()) {
5959
if (input.state != "connected") continue;
6060

61-
console.log(input.name);
62-
63-
input.onmidimessage = this.makeMessageCb(input.id);
61+
input.onmidimessage = (e) =>
62+
this.trigger("midimessage", input.id, e.data);
6463
}
6564

6665
// Detect new devices being connected
6766
this.midiAccess.onstatechange = (evt) => {
6867
if (evt.port.type == "input" && evt.port.state == "connected") {
6968
console.log(
70-
"new device connected:",
69+
"MIDI device connected:",
7170
evt.port.name,
7271
"PORT:",
7372
evt.port.id
7473
);
7574

76-
evt.port.onmidimessage = this.makeMessageCb(evt.port.id);
75+
evt.port.onmidimessage = (e) =>
76+
this.trigger("midimessage", evt.port.id, e.data);
7777
}
7878
};
7979
}
8080

81-
// Create an onmidimessage callback for an input port
82-
makeMessageCb(deviceId) {
83-
// Callback when a MIDI message is received
84-
function onMidiMessage(evt) {
85-
var str = "";
86-
for (var i = 0; i < evt.data.length; i++) {
87-
str += "0x" + evt.data[i].toString(16) + " ";
88-
}
89-
// console.log(str);
90-
91-
// Send the device name and the data to callbacks
92-
this.trigger("midimessage", deviceId, evt.data);
93-
}
94-
95-
return onMidiMessage.bind(this);
96-
}
97-
9881
// Send a message to all MIDI devices
9982
broadcast(msg, timestamp) {
10083
if (!midi) return;

0 commit comments

Comments
 (0)