'Python: Listen for keys only when application is in focus

I have a small project on doing a audio-player for the console window. It's all going great, but I'm struggling with one small detail. I want when the user presses a key, space for example, to pause the audio, and I've achieved that. The problem is: the audio is pausing even when the player is not on focus.

For an example, I put some music on the player, and go the web browser. If space is pressed while navigating in the browser, the audio will stop.

I want the program to listen ONLY when the app is focused. Here is a part of my code:

def play_pause():
    global buttons
    
    if '⏸' in buttons:
        buttons = (' ' * 21) + '⏮  ⯈  ⏭'
    else:
        buttons = (' ' * 21) + '⏮  ⏸  ⏭'
    
    audio.play_pause_audio()

def controller(key):
    if key == Key.space or key == Key.media_play_pause:
        play_pause()

    # TO DO:
    # if key == Key.left or key == Key.media_previous:
    #     pass
    # if key == Key.right or key == Key.media_next:
    #     pass

    draw_player()

def start_player(audio_name):
    global current_audio
    current_audio = audio_name

    draw_player()

    with Listener(on_press=controller) as listener:
        listener.join()

I'm currently using pynput: from pynput.keyboard import Key, Listener.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source