music21

9.9.1 · active · verified Fri Apr 17

music21 is a Toolkit for Computer-Aided Musical Analysis and Computational Musicology. It provides objects and methods to represent musical notation and analytical concepts, allowing for programmatic manipulation, analysis, and generation of musical data. Version 9.9.1 is the latest release, with a frequent release cadence, often addressing Python compatibility and adding new features for import/export.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates creating a simple musical stream with a few notes and displaying it. The `s.show()` method relies on external applications like MuseScore or LilyPond to render scores. Ensure you have one installed and configured for optimal results. Alternatively, you can save the output to a file (e.g., MusicXML or MIDI).

import music21
from music21 import note, stream, tempo

# Create a musical stream (like a score or a part)
s = stream.Stream()
s.append(tempo.MetronomeMark(number=120))

# Add some notes
n1 = note.Note('C4')
n1.duration.type = 'quarter'
s.append(n1)

n2 = note.Note('D4')
n2.duration.type = 'quarter'
s.append(n2)

n3 = note.Note('E4')
n3.duration.type = 'half'
s.append(n3)

# Display the stream (requires an external MusicXML viewer like MuseScore)
# If no viewer is installed, this might open a browser with an XML file or fail.
# For headless environments, consider s.write('midi') or s.write('musicxml').
try:
    s.show()
except Exception as e:
    print(f"Could not display score: {e}")
    print("Try installing MuseScore or using s.write('musicxml', fp='my_score.xml')")

view raw JSON →