0

I am currently trying to make a simple python script for creating speech data.

The idea with the script is that is starts recording using pyaudio, when a key is pressed and hold down, and stops recording when the key is released.

I am currently a bit confused on how i should implement the while key hold / stop at release mechanism.

i found this library keyboard , but can't make sense whether it incorporates this form of mechanism?

open_ey
  • 1
  • 2
  • 1
    See comment of [this](https://stackoverflow.com/questions/40649634/determine-length-of-keypress-in-python) question. That might help you. – P. Siehr Jul 03 '17 at 11:41
  • Just seem like a bit too much for this simple task @P.Siehr – open_ey Jul 03 '17 at 12:05

1 Answers1

2

According to this code in library "keyboard"'s source, it do provide such mechanism to detect if a key is currently pressed. so you can just do a while loop to check whether user has released that key.

#/usr/bin/python
# file: __init__.py
# ...
def is_pressed(key):
    """
    Returns True if the key is pressed.
        is_pressed(57) -> True
        is_pressed('space') -> True
        is_pressed('ctrl+space') -> True
    """
    _listener.start_if_necessary()
    if is_number(key):
        return key in _pressed_events
    elif len(key) > 1 and ('+' in key or ',' in key):
        parts = canonicalize(key)
        if len(parts) > 1:
            raise ValueError('Cannot check status of multi-step combination ({}).'.format(key))
        return all(is_pressed(part) for part in parts[0])
    else:
        for event in _pressed_events.values():
            if matches(event, key):
                return True
        return False
Sajuuk
  • 2,197
  • 3
  • 16
  • 32
  • `while keyboard.is_pressed('space'):` gives me error message: `raise ImportError('You must be root to use this library on linux.') ImportError: You must be root to use this library on linux.` And running it as sudo gives me error message: `IOError: [Errno 1] Operation not permitted: '/dev/uinput'` – open_ey Jul 03 '17 at 12:10
  • `keyboard` seems only to work with windows and linux. Anything that both works on linux an windows. – open_ey Jul 03 '17 at 15:11
  • @open_ey, Are you using MacOS? – Sajuuk Jul 04 '17 at 07:47
  • Is there anything for Mac? – tonix Dec 25 '17 at 23:45