Sitemap
Play With Python

Learn Python and programming through fun and games.

Member-only story

Drum Machine

7 min readJan 20, 2026

--

Press enter or click to view image in full size
Our Drum Machine.

The Musical Instrument Digital Interface (MIDI) allows electronic instruments to be controlled by a computer.

MIDI commands specify when to play a note or beat, which instrument should play it, and at what volume, among other details.

PyGame speaks MIDI. It can also draw a GUI on the screen and accept mouse and keyboard inputs. It is perfect for creating a digital musical instrument.

Let’s Build a Drum Machine

Our digital musical instrument will keep a complex beat, using as many as 20 different instruments. By dividing the time into 32 steps, we can create rhythms that are complex enough to be interesting by themselves, even without melodic accompaniment.

You can easily expand upon this program, adding instruments, or increasing the steps to 64 or 128 or more, and adding more presets.

Presets are rhythms from different genres, such as rock, bossa nova, samba, salsa, or disco.

You can change the speed, add reverb, swing, and delay.

Here is what the code looks like:

import pygame
import pygame.midi
import time
import random

# --- CONFIGURATION & CONSTANTS ---
SCREEN_WIDTH = 1350
SCREEN_HEIGHT = 850
FPS = 60

# Colors
DARK_GRAY =…

--

--

Simon Quellen Field
Simon Quellen Field

Written by Simon Quellen Field⁠

Simon Quellen Field is a science writer and novelist currently experimenting with shorter works. Find his books at scitoys.com/books or his website scitoys.com.

Play With Python
Play With Python

Published in Play With Python

Learn Python and programming through fun and games.