User-Defined Opcode Database

KeyOnce

Returns '1' once if a certain key has been pressed or released.

Download UDO File

Description

Returns '1' once if a certain key has been pressed or released. Needs the output of a sensekey opcode. Note that just one sensekey opcode is allowed in an instrument.

Syntax

kdown, kup KeyOnce key, kd, kascii

Performance

key - first output of a sensekey opcode
kd - second output of a sensekey opcode
kascii - ascii code of the key you want to check (for instance 32 for the space bar)
kdown - returns '1' in the k-cycle kascii has been pressed
kup - returns '1' in the k-cycle kascii has been released

Code

  opcode KeyOnce, kk, kkk
key, kd, kascii    xin 
knew      changed   key
kdown     =         (key == kascii && knew == 1 && kd == 1 ? 1 : 0)
kup       =         (key == kascii && knew == 1 && kd == 0 ? 1 : 0)
          xout      kdown, kup
  endop

Examples

<CsoundSynthesizer>
<CsOptions>
-n -m0
</CsOptions>
<CsInstruments>
sr = 44100
ksmps = 32
nchnls = 2
0dbfs = 1

  opcode KeyOnce, kk, kkk
;returns '1' just in the k-cycle a certain key has been pressed (kdown) or released (kup)
key, kd, kascii    xin ;sensekey output and ascii code of the key (e.g. 32 for space)
knew      changed   key
kdown     =         (key == kascii && knew == 1 && kd == 1 ? 1 : 0)
kup       =         (key == kascii && knew == 1 && kd == 0 ? 1 : 0)
          xout      kdown, kup
  endop

  opcode KeyStay, k, kkk
;returns 1 as long as a certain key is pressed. make sure that automatic key repeats are disabled on your computer
key, kd, kascii    xin ;sensekey output and ascii code of the key (e.g. 32 for space)
kprev     init      0 ;previous key value
kout      =         (key == kascii || (key == -1 && kprev == kascii) ? 1 : 0)
kprev     =         (key > 0 ? key : kprev)
kprev     =         (kprev == key && kd == 0 ? 0 : kprev)
          xout      kout
  endop

instr 1
          prints    "PRESS THE SPACE BAR!\n"
key, kd   sensekey
kdwn,kup  KeyOnce   key,kd,32
kstay     KeyStay   key,kd,32
 if kdwn == 1 then
          printks   "SPACE BAR PRESSED!\n", 0
 endif
 if kup == 1 then
          printks   "SPACE BAR RELEASED!\n", 0
 endif
 if kstay == 1 then
          printks   "SPACE BAR HOLD!\n", 1
 endif
endin


</CsInstruments>
<CsScore>
i 1 0 100
</CsScore>
</CsoundSynthesizer>

Credits

joachim heintz 2010


Previous Home Next
MS2S   KeyStay