Play Sound When Keyboard Key Pressed (Python3)

I bought some Duckeys.

They come with software to make the computer quack when the key is pressed, but it's only available on Windows and Mac.

This snippet uses Python to watch for keypresses and play audio when one is detected. The example goes further and plays a quack if the pressed key is one with a Duckey on.

Details

  • Language: Python3

Snippet

from pynput.keyboard import Key, Listener
import playsound


def on_press(key):
    playsound.playsound('foo.mp3')

def on_release(key):
    return

# Listen for keypresses
with Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

Example

#!/usr/bin/env python3
#
# pip install pynput playsound

from pynput.keyboard import Key, Listener
import playsound


# Which keys have ducks on them?
KEYS = [
    Key.esc,
    Key.print_screen,
    Key.f5
    ]

# Location of the sound to play
SOUND = '/usr/local/share/quack.mp3'

def on_press(key):
    if key in KEYS:
        #print("Quack")
        playsound.playsound(SOUND)


def on_release(key):
    return

# Collect events until released
with Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

Requires

Video