Skip to content

Instantly share code, notes, and snippets.

@micolous
Created December 21, 2020 03:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save micolous/8a747aa39c250b933b174dd140b2929b to your computer and use it in GitHub Desktop.
Save micolous/8a747aa39c250b933b174dd140b2929b to your computer and use it in GitHub Desktop.
MIDI-controlled PTT in Discord
// ==UserScript==
// @name Discord: MIDI controlled PTT
// @version 1
// @grant none
// @match https://discord.com/*
// ==/UserScript==
/*
* This listens for any MIDI device sending a "note on" or "note off" event,
* and rebinds this to F9.
*
* This should allow you to use any MIDI device as a way to activate Discord's
* push-to-talk in the browser, even when it doesn't have focus!
*
* There's nothing specific in this script to Discord's UI, and should be
* trivial to adapt to other sites.
*/
(() => {
// We're going to send F9.
const KEYCODE = 120;
// MIDI command codes, we don't care which note.
const NOTE_ON = 9;
const NOTE_OFF = 8;
// Send a keystroke to the page.
function press(release) {
document.activeElement.dispatchEvent(new KeyboardEvent(
release ? 'keyup' : 'keydown', {keyCode: KEYCODE, bubbles: true, cancelable: true}));
}
navigator.requestMIDIAccess().then(
(midi) => {
// Listen on all MIDI input devices.
const inputs = Array.from(midi.inputs.values());
for (const input of inputs) {
input.addEventListener('midimessage', (m) => {
const cmd = m.data[0] >> 4;
if (cmd == NOTE_ON) {
press();
} else if (cmd == NOTE_OFF) {
press(true);
}
});
}
},
(err) => console.log('midi fail:', err)
);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment