0

I'm trying to create a python program that measures trill velocity of pianists. Trills are a musical ornament consisting of a rapid alternation between two adjacent keys on the piano, so I think this can be simulated with two keys of the pc keyboard, like "K" and "O". Keys would be pressed at a frequency of 10 beats per second or higher.

Is there a way to register in Python the time when a keystroke happens?

Once obtained that data, I could use it to make statistics, etc.

Quaerendo
  • 107
  • 6
  • 2
    See https://stackoverflow.com/questions/24072790/detect-key-press-in-python for detecting key presses, then record the current time when a keypress is detected. – Ollie Apr 26 '19 at 10:45
  • Apart from the question being too broad, computer keyboards behave quite differently than piano keys, so the results would probably not be very meaningful. – mkrieger1 Apr 26 '19 at 10:45
  • It's true that they are different key types, but there is a correlation between the speed with which you trill on both of them. – Quaerendo Apr 26 '19 at 19:27

2 Answers2

0

Modifying keyboard library's pressed_keys example, as follows, I have achieved what I was attempting. However, for some reason, times are printed twice on the screen for each keystroke. Why does this happen? How could it be fixed?

"""
Prints the scan code of all currently pressed keys.
Updates on every keyboard event.
"""
import sys
sys.path.append('..')
import keyboard
import time
def print_pressed_keys(e):
    #line = ', '.join(str(code) for code in keyboard._pressed_events)
    # '\r' and end='' overwrites the previous line.
    # ' '*40 prints 40 spaces at the end to ensure the previous line is cleared.
    #print('\r' + line + ' '*40, end='')
    a=time.clock()
    print(a)

keyboard.hook(print_pressed_keys)
keyboard.wait()
Quaerendo
  • 107
  • 6
-1

You can use the time class. Depending on how much precision do you need, but you could do:

times = []

key_stroke:
    times.append(time.time()) #time.clock() for more precision

For the key detection method, follow this link. Also if you need to include more information on each key or distinguish between key presses, create a class and add one field with the time and other with the key.

Nassiel
  • 109
  • 1
  • 6