Hi, I'm a coursera's ChucK course student, in the lectures, Ge used HIDs to handle keyboard input, so this snippet should help (I'm commenting the code for clarity).
// HID stands for human-interface-device, also this is an event,
// see below for more info
Hid hid;
// This is a message, this will hold the event's (keypress) information.
HidMsg msg;
// We should define a device number since we would have multiple keyboards
// attached to our computer, 0 would do on most cases but you can try 1, or 2
// if that doesn't work.
0 => int device_number;
// We check if the device attach with ChucK was successful, otherwise the program
// would end inmediately
if(!hid.openKeyboard(device_number)) me.exit();
<<<"Keyboard:", hid.name(), " ready!">>>;
// We setup a simple sound chain for demonstration pruposes only
BeeThree organ => JCRev rev => dac;
.05 => rev.mix;
// And repeat forever, see how the keyboard input is something that would happen
// *forever*, a keypress can occur anytime so we need to stay alert until a new
// event comes in
while(true) {
// Events are things that happens sometime, in ChucK this mains basically
// hold ourselves until the event appears (thats why we wain for the event
// ChucKing it to now)
hid => now;
// When our wait finishes: check all the messages that came from the keyboard
// using the recv function, and passing msg as the holder of the information
while(hid.recv(msg)) {
// we check if the message is a buttondown message, in that case:
if(msg.isButtonDown()) {
// We show the ascii value of the key pressed
<<< "Button down:", msg.ascii >>>;
// and make our generator sound, see how we check if the
// frequency too much high we simply discard this message
msg.ascii => Std.mtof => float freq;
if(freq > 20000) continue;
freq => organ.freq;
1 => organ.noteOn;
// this will make sure the sound will keep for a minimum amount of
// time, otherwise, concurrent events may stop before even commencing
80::ms => now;
} else {
// If we're not in a buttondown event, just assume it's a key has been
// left out and shut down the sound.
<<< "Button up:", msg.ascii >>>;
1 => organ.noteOff;
}
}
}