简体   繁体   English

如何检测键盘输入以使用python播放声音?

[英]How can I detect keyboard input to play a sound with python?

I am making a program that will play a sound when you press a key (or just type) on the keyboard. 我正在编写一个程序,当您按下键盘上的一个键(或只是键入)时,该程序将播放声音。

I just started to work on it, and I am trying to use pygame.key.get_pressed() to check for keyboard input. 我刚刚开始研究它,并且尝试使用pygame.key.get_pressed()检查键盘输入。 I got to here with the code: 我到了这里的代码:

from pygame import init, key

init()

spam = []

while True:
    spam = key.get_pressed()
    if True in spam:
        print('KEY PRESSED')
    elif False in spam:
        print('NONE')

It works by checking if a True value is in spam ( spam is the name of the list pygame returns). 它通过检查spam是否为True值来工作( spampygame返回的列表的名称)。 key.get_pressed returns a list of True/False values for every key, True if pressed, False if not. key.get_pressed返回列表True/False值,每个按键, True按下如果, False如果不是。

The problem with this code is that when I run it, it only outputs None . 此代码的问题在于,当我运行它时,它仅输出None This means that I am not detecting the keyboard input. 这意味着我没有检测到键盘输入。

If anyone knows how to fix this, or a better way to do it, I would greatly appreciate it! 如果有人知道如何解决此问题,或者有更好的解决方法,我将不胜感激!

Thanks! 谢谢!

pygame.key.get_pressed() gets the states of all keybord buttons. pygame.key.get_pressed()获取所有键盘按钮的状态。 It returns a list. 它返回一个列表。
But, note the values which are returned by pygame.key.get_pressed() are only updated when the key event is get events from the queue by pygame.event.get() . 但是,请注意,仅当关键事件是pygame.event.get()从队列中获取事件时,才会更新pygame.key.get_pressed()返回的值。 In simple words, pygame.key.get_pressed() only works, if there is an event loop, too. 简而言之, pygame.key.get_pressed()仅在存在事件循环的情况下才有效。

You can evaluate a specific key (eg space key): 您可以评估特定的键(例如空格键):

allKeys = pygame.key.get_pressed()
spam = allKeys[pygame.K_SPACE] 

If you want to evaluate if any key is pressed, then you've to evaluate if any() value in allKeys is True : 如果要评估是否按下了任何键,则必须评估allKeys any()allKeysTrue

allKeys = pygame.key.get_pressed()
anyKey = any([k for k in allKeys if k == True])

Another solution would be to check if the KEYDOWN event occurred. 另一个解决方案是检查KEYDOWN事件是否发生。 The next pending event can be fetched by pygame.event.get() : 可以通过pygame.event.get()获取下一个未决事件:

keyPressed = False
for event in pygame.event.get():
    if event.type == pygame.KEYDOWN: 
        keyPressed = True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM