Python Music21 Music Theory — Core Concepts
What music21 does
Music21 is a Python toolkit for computational musicology, developed at MIT. It models Western music theory — notes, intervals, chords, keys, scales, meters, counterpoint rules — as Python objects. It can parse MusicXML, MIDI, Humdrum, ABC notation, and MuseData files, analyze them, and export results as notation, MIDI, or Lilypond scores.
Install with pip install music21. For notation display, configure a MusicXML viewer like MuseScore.
Core objects
Notes and rests
from music21 import note, duration
n = note.Note("C#5") # C-sharp in octave 5
n.quarterLength = 1.5 # dotted quarter note
Every note has a pitch (name, octave, frequency, MIDI number), duration, and optional properties like dynamics and articulations.
Chords
from music21 import chord
c = chord.Chord(["C4", "E4", "G4"])
print(c.commonName) # 'Major Triad'
print(c.root()) # C4
Music21 can identify chord types, inversions, and Roman numeral labels in context.
Streams
Streams are the container hierarchy: Score > Part > Measure > Note/Chord/Rest. They represent the temporal layout of music.
from music21 import stream
s = stream.Stream()
s.append(note.Note("D4", quarterLength=1))
s.append(note.Note("E4", quarterLength=1))
s.append(note.Note("F#4", quarterLength=1))
s.append(note.Note("G4", quarterLength=2))
Key and harmony analysis
from music21 import converter
score = converter.parse("bach_chorale.xml")
key = score.analyze("key")
print(key) # e.g., "G major"
The analyze("key") method uses the Krumhansl-Schmuckler algorithm, which correlates pitch-class distribution against major and minor key profiles. You can also get the correlation coefficients for each candidate key.
Roman numeral analysis
from music21 import roman
rn = roman.RomanNumeral("V7", "C")
print(rn.pitches) # G4, B4, D5, F5
This lets you generate chord progressions in any key, check voice leading, or label existing harmonies.
The built-in corpus
Music21 ships with thousands of scores — Bach chorales, folk songs, Beethoven string quartets, Monteverdi madrigals. Access them directly:
from music21 import corpus
bach = corpus.parse("bach/bwv66.6")
soprano = bach.parts[0]
print(len(soprano.recurse().notes)) # number of notes in soprano voice
The corpus is invaluable for statistical studies — analyzing chord progressions across 371 Bach chorales, comparing melodic intervals in different centuries, or building training data for generative models.
Interval and scale tools
from music21 import interval, scale
i = interval.Interval("P5") # perfect fifth
print(i.semitones) # 7
sc = scale.MajorScale("Eb")
print([str(p) for p in sc.getPitches("Eb4", "Eb5")])
Music21 handles enharmonic spelling (C♯ vs D♭), interval classification (augmented, diminished, compound), and exotic scales (whole-tone, octatonic, modes).
Visualization and export
score.show()— opens the score in MuseScore or another configured viewerscore.show("midi")— plays through a MIDI synthesizerscore.show("text")— prints a text representationscore.write("musicxml", "output.xml")— exports to MusicXML
Common misconception
Music21 is not an audio library. It works with symbolic music (notes, rhythms, keys) — not sound waves. To analyze audio recordings, use Librosa for feature extraction and then optionally convert pitch estimates into music21 note objects for theory-level analysis.
How it fits with other tools
Music21 provides the theory layer. Combine it with pretty_midi for MIDI I/O, Librosa for audio features, Lilypond for publication-quality engraving, and PyTorch/TensorFlow for training generative music models on music21-extracted features.
One thing to remember: Music21 encodes centuries of music theory as Python objects — giving you programmatic access to keys, chords, intervals, counterpoint rules, and a vast corpus of classical scores.
See Also
- Python Arcade Library Think of a magical art table that draws your game characters, listens when you press buttons, and cleans up the mess — that's Python Arcade.
- Python Audio Fingerprinting Ever wonder how Shazam identifies a song from just a few seconds of noisy audio? Audio fingerprinting is the magic behind it, and Python can do it too.
- Python Barcode Generation Picture the stripy labels on grocery items to understand how Python can create those machine-readable barcodes from numbers.
- Python Cellular Automata Imagine a checkerboard where each square follows simple rules to turn on or off — and suddenly complex patterns emerge like magic.
- Python Godot Gdscript Bridge Imagine speaking English to a friend who speaks French, with a translator in the middle — that's how Python talks to the Godot game engine.