Skip to content

Instantly share code, notes, and snippets.

@Gadgetoid
Created March 11, 2025 13:31
Show Gist options
  • Select an option

  • Save Gadgetoid/2731c34b16cb76007658d75e8fae04a2 to your computer and use it in GitHub Desktop.

Select an option

Save Gadgetoid/2731c34b16cb76007658d75e8fae04a2 to your computer and use it in GitHub Desktop.
A silly way to turn your keyboard into an avalanche of drum sounds
#!/usr/bin/env python
from pynput import keyboard
import pygame
import os
import random
import glob
DRUM_FOLDER = "drums2"
BANK = os.path.join(os.path.dirname(__file__), DRUM_FOLDER)
pygame.mixer.init(44100, -16, 1, 512)
pygame.mixer.set_num_channels(32)
files = glob.glob(os.path.join(BANK, "*.wav"))
files.sort()
samples = [pygame.mixer.Sound(f) for f in files]
def on_press(key):
print(key)
try:
sample = ord(key.char) % len(samples)
samples[sample].play(loops=0)
except AttributeError:
random.choice(samples).play(loops=0)
with keyboard.Listener(on_press=on_press) as listener:
listener.join()
@Gadgetoid
Copy link
Author

Gadgetoid commented Mar 11, 2025

If you're launching this from Terminal then you need to delve into Privacy & Security -> Input Monitoring and enable Terminal.app. There's no need to quit and relaunch terminal, though you'll need to relaunch the Python program.

Needs pynput and pygame ... could probably just use the latter, but who likes event pumps anyway.

Known issues:

  1. Completely silly
  2. For entertainment purposes only
  3. Re-triggers when you hold a key... figure that out yourself
  4. Mods have random sounds, alphas are constant (char code modulo the sample bank size)

I was lazy so I grabbed the Drum samples from my old Drum HAT code at https://github.com/pimoroni/drum-hat/tree/master/examples/drums2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment