Sound latency linked to keystroke

I am trying to develop a temporal calibration experiment where the sound has to occur when a key stoke occurs and sometimes a few milliseconds after that. Is there a way to detect keystrokes and align the sound with the keystroke?