Friday, December 17, 2010

How To: Convert MIDI Note Data To Simulated ASCII Code Keystrokes (Mac OS X)

Something that I have always wanted to do is convert MIDI notes to simulated computer keyboard presses. I am sure that there are many ways of achieving this, but here is a quick and easy way using MIDIPipe by SubtleSoft (Nico Wald) and AppleScript. MIDIPipe is a great piece of software that can convert and manipulate MIDI data in a range of ways.

In my simple example, I have plugged in my 25-key MIDI keyboard, and I want to simulate a keyboard keystroke for every MIDI note-on event that I send when I press a music key. In particular, I want to use the MIDI note number as the ASCII code of the keyboard key I want to "press".

This is achieved by creating a new, blank pipe in MIDIPipe. The first process in this pipe is the MIDI In tool, followed by the AppleScript Trigger tool. The MIDI input tool will allow MIDIPipe to see the keyboard (and read music notes that I play), and the AppleScript Trigger tool will then respond to those music notes. Note that this is a very simple example, but might be a good building block to build upon in some way if needed.


The only parameter to set for the MIDI Input tool is the MIDI device, which in this case is the music keyboard.



The relevant AppleScript is as follows:

on runme(message)
set key_out to item 2 of message
if (item 1 of message = 144) and (item 3 of message > 0) then
tell application "System Events"
keystroke (ASCII character key_out)
end tell
end if
end runme


This will send the relevant ASCII keystrokes to whichever application is currently active and in focus.

0 comments: