Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

python - How Do I Play An Audio Whenever I Click On a Specific Key On The Keyboard?

So, my idea is to create a program (using the "Keyboard" module) that, while I am pressing on a key ("Enter", in this case), a sound is played (only once), as soon as I stop pressing that key, another sound would be played (only once). In other words, NASA uses a communications system in which, when a "call" starts, a "beeeep" is played, when the "call" is ended (like an "Over") a "beeeeep" is played again. This was my first attempt:

import keyboard
import pygame

def BeepOn():
    pygame.mixer.init()
    pygame.mixer.music.load("Mic On.mp3")
    pygame.mixer.music.play(loops=0)
    pygame.mixer.music.set_volume(0.50)

def BeepOff():
    pygame.mixer.init()
    pygame.mixer.music.load("Mic Off.mp3")
    pygame.mixer.music.play(loops=0)
    pygame.mixer.music.set_volume(0.50)

while True:
    if keyboard.on_press_key('Enter'):
        BeepOn()

    if keyboard.on_release_key('Enter'):
        BeepOff()

    if keyboard.is_pressed('End'):
        exit()

Attention: I would like you to just have to click on one key instead of two. I hope I explained it well! I look forward to an answer (however stupid it may be). Regards, Diogo Matos

question from:https://stackoverflow.com/questions/65832715/how-do-i-play-an-audio-whenever-i-click-on-a-specific-key-on-the-keyboard

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here:

import pygame

#Condition for while loop
running = True



def BeepOn():
    pygame.mixer.init()
    pygame.mixer.music.load("Mic On.mp3")
    pygame.mixer.music.play(loops=0)
    pygame.mixer.music.set_volume(0.50)

def BeepOff():
    pygame.mixer.init()
    pygame.mixer.music.load("Mic Off.mp3")
    pygame.mixer.music.play(loops=0)
    pygame.mixer.music.set_volume(0.50)


while running:
    
    for event in pygame.event.get():
            #Tests for quit
            if event.type == pygame.QUIT:
                running = False
            #Tests if enter is pressed
            if event.type = pygame.KEYDOWN:
              if Event.key == pygame.K_RETURN:
                BeepOn()

            #Tests if enter is released
            if event.type = pygame.KEYUP:
              if Event.key == pygame.K_RETURN:
                BeepOff()
pygame.quit()

I hope this helps, I'm not familiar with the keyboard module, so I just did it all from pygame. (: If this helps please let me know...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...