【问题标题】:record while key is pressed, stop when key is released按下键时记录,松开键时停止
【发布时间】:2017-07-03 11:35:56
【问题描述】:

我目前正在尝试制作一个简单的 python 脚本来创建语音数据。

脚本的想法是当按下并按住一个键时使用pyaudio 开始录制,并在释放该键时停止录制。

我目前对如何实现while key hold / stop at release mechanism. 有点困惑

我找到了这个库 keyboard ,但它是否包含 这种形式的机制?

【问题讨论】:

  • 查看this问题的评论。这可能会对你有所帮助。
  • 对于这个简单的任务来说似乎有点太多了@P.Siehr

标签: python macos keyevent


【解决方案1】:

根据库“键盘”源中的this code,它确实提供了这种机制来检测当前是否按下了键。所以你可以做一个while循环来检查用户是否释放了那个键。

#/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

【讨论】:

  • while keyboard.is_pressed('space'): 给我错误消息:raise ImportError('You must be root to use this library on linux.') ImportError: You must be root to use this library on linux. 并以 sudo 运行它给我错误消息:IOError: [Errno 1] Operation not permitted: '/dev/uinput'
  • keyboard 似乎只适用于 windows 和 linux。任何可以在 linux 和 windows 上运行的东西。
  • @open_ey,您使用的是 MacOS 吗?
  • 有什么适用于 Mac 的吗?
猜你喜欢
  • 2019-01-11
  • 2012-05-31
  • 1970-01-01
  • 2014-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-26
  • 2015-05-01
相关资源
最近更新 更多