Simple Keys — Modularized Key Mapping

Csound can read real-time input from an ASCII keyboard with the sensekey opcode. This is a convenient solution for doing things such as emulating a musical keyboard, or triggering loops.

Since I’m always looking for ways of modularizing code, I came up with a solution that allows me to map ASCII keys using i-events instead of hard coding bindings directly to an instrument. My solution still needs a little more work, though I’m confident that the final product will be fairly elegant. Well, as elegant as things get with Csound.

You can give it a try by downloading and running simple_keys.csd. It’s a one octave sinusoidal piano, that uses the following key map (lowercase only):

 s d  g h j
z x cv b n m,

Technical Overview

Instead of explicitly mapping each key from within an instrument, I worked a little Csound ftable trickery to make it so that I could bind keys using score events. A new key map is created like this with an i-event inside the orchestra:

event_i "i", $NewKeyMap, 0, 1, i_z, cpspch(8.00), 2

The score equivalent would be:

i $NewKeyMap 0 1 122 261.62556 2

The i-variable i_z holds the value of the ASCII code for the letter “z”, which is 122. The fifth parameter is the frequency that is to be associated with “z”. The last parameter is the ftable number of a stored single cycle wave.

When instrument NewKeyMap is called, it appends these parameters to an f-table. This f-table, called record_table, acts as an array of records, where each record stores an ASCII key code, frequency and f-table number.

The Listen instrument waits and listens for key presses. Whenever a key is pressed, the ASCII code of that key is checked against every record inside of record_table. If a match is found, then an event to instrument Synth is generated. The frequency and ftable number from the record is passed along the event as pfields.

I like this approach because I can reuse these three instruments in many ways without modification. For example, I could design a microtonal version of the keyboard just by creating a different set of events to instrument NewKeyMap, and I could use different timbres by generating different wave tables.

One thought on “Simple Keys — Modularized Key Mapping

  1. Pingback: The Csound Blog » Making Records