Created
December 21, 2020 03:44
-
-
Save micolous/8a747aa39c250b933b174dd140b2929b to your computer and use it in GitHub Desktop.
MIDI-controlled PTT in Discord
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==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