What is music21?
Music21 is a set of tools for helping scholars and other active listeners answer questions about music quickly and simply. If you’ve ever asked yourself a question like, “I wonder how often Bach does that” or “I wish I knew which band was the first to use these chords in this order,” or “I’ll bet we’d know more about Renaissance counterpoint (or Indian ragas or post-tonal pitch structures or the form of minuets) if I could write a program to automatically write more of them,” then music21 can help you with your work.
How simple is music21 to use?
Extremely. After starting Python and typing "from music21 import *"
you can do all of these things with only a single line of music21 code:
Display a short melody in musical notation:
3/4 c4 d8 f g16 a g f#").show()
Print the twelve-tone matrix for a
tone row (in this case the opening of Schoenberg's Fourth String Quartet):
print (serial.rowToMatrix([2,1,9,10,5,3,4,0,8,7,6,11]) )
or since all the 2nd-Viennese school rows are already available as objects, you can type:
print (serial.getHistoricalRowByName('RowSchoenbergOp37').matrix() )
Convert a file from Humdrum's **kern data format to MusicXML for editing in Finale or Sibelius:
With five lines of music21 code or less, you can:
Prepare a thematic (incipit) catalog of every Bach chorale that is in 3/4:
catalog = stream.Opus()
for workName in corpus.chorales.Iterator():
work = converter.parse(workName)
firstTS = work.recurse().getElementsByClass('TimeSignature')
if firstTS.ratioString == '6/8':
Google every motet in your
database that includes the word ‘exultavit’ in the superius
(soprano) part (even if broken up as multiple syllables in the source
file) to see how common the motet's text is (assuming you have a bunch
of motets in "listOfMotets"):
for motet in listOfMotets:
superius = motet
lyrics = text.assembleLyrics(part)
if 'exultavit' in lyrics:
webbrowser.open('http://www.google.com/search?&q=' + lyrics)
Add the German name (i.e., B♭ = B, B = H, A♯ = Ais) under each note of a Bach chorale and show the new score:
bwv295 = corpus.parse('bach/bwv295')
for thisNote in bwv295.recurse().notes:
Of course, you are never limited to just using five lines to do tasks with
music21. In the demos folder of the
music21 package and in the sample problems page
(and throughout the documentation) you’ll find examples of more complicated problems
that music21 is well-suited to solving, such as
cataloging the rhythms of a piece from most to
Music21 builds on preexisting frameworks and technologies such as Humdrum, MusicXML, MuseData, MIDI, and Lilypond but music21 uses an object-oriented skeleton that makes it easier to handle complex data. But at the same time music21 tries to keep its code clear and make reusing existing code simple. With music21 once you (or anyone else) has written a program to solve a problem, that program can easily become a module to be adapted or built upon to solve dozens of similar (but not identical) problems.
Interested in learning more?
Music21 v5.7 is the fourth and final release in the v5 series. It brings under the hood fixes -- lots of bug fixes and speed ups and some new features -- from 126 commits since last October.
Download by running from command line:
pip install --upgrade music21
This is the last release of the v5 series so that work on v6 which may bring some backwards incompatible changes -- all deprecated features will be removed, as will support for Python 3.5 (by the time v6 is released, Py3.8 will be out and this keeps w/ music21 policy of supporting the last three Python releases). The release of v5.7 also marks the End-of-Life for music21 v4 (the last release to support Python 2.7); if someone wants to continue supporting v4/Python 2.7 in music21, please let me know, but I'm so happy with how quickly almost all of us have moved to Python 3. Looking forward to major tablature improvements, SMuFL support, and much faster development thanks to "f-strings" in v6.
The music21 user community continues to be active and robust as attested by the number of contributed features below. Thanks for keeping me sustained during my non-music Admin time! Among the most notable improvements are (in reverse chronological order):
Type hints on major objects and functions in the library and the promise of more (once Py3.5 is dropped) soon. Those who use fancy IDEs like PyCharm will reap major bug checks!
The most extensive typo-checking / spell-checking / linting ever done to music21 -- the code now has that new car smell.
Stream.measures(4, "5a") -- measure suffixes work in many more places in the code.
Pizzicato notes export properly in MusicXML
Improvements to MEI accidental handling (kudos @raffazizzi
KeySignatures work better in multi-voice contexts (thanks @pconerly
Bugs that made
.getContextByClass() sometimes inconsistent (especially with forward searches) fixed.
Harmony objects (ChordSymbols, etc.) sort before Notes so that the harmony of a note at the offset can be found easier. And proper musicxml offset support (thanks @a-papadopoulos
Chord.notes gives direct access to the underlying Note objects that make up a Chord. Chords also get a good
Added Neo-Riemannian analysis features (thanks @MarkGotham
) and triads can now know which hexatonic system they belong to.
Fixes to MusicXML chord input.
Barlines now use "type=double" instead of "style=double", since in v6 they will get full
User's Guide gets the long awaited Chapter 58 on Sites and Contexts for advanced users.
Clefs get a
.name property so that the class does not need to be parsed.
Grace notes no longer cause obscure bugs in
A bug in Interval.direction for some perfect intervals is fixed (thanks @ryaanahmed
team for identifying the bug)
As always, I want to acknowledge MIT Music and Theater Arts and the School of Humanities, Arts, and Social Sciences for encouraging the development of music21. Founding contributions to music21 were made by the Seaver Institute and the National Endowment for the Humanities.
Version 5.5 brings some small but important improvements to
music21 and is a maintenance release. V5.5 is the first release to no longer support Python 3.4, so please use Python 3.5 or higher to upgrade.
Important changes and bugfixes.
- Chord.commonName gets many improvements, detecting for instance, the differences between dominant-seventh chords and augmented sixths.
- much better metadata on Bach Chorals (thanks Norman!)
- Stream.voiceToParts() is much improved and gets an optional
separateById keyword argument which will only merge voices whose
.id matches. -- this is very exciting to me from an analytical perspective and one reason I decided to release now.
- Volpiano is upgraded to a full conversion method. Most people will go, "buh??" people who work with Gregorian chant will rejoice.
- obj.activeSite is set more reliably.
- better error messages if a stream cannot be chordified.
- ABC parses all major and minor keys properly -- there were a few bugs especially on sharp keys in minor before. (Thanks @a-papadopoulos )
- "Cad64" is now an acceptable RomanNumeral alternative for "I64" for all you theorists out there who cringed when writing it. Resolves to I64 in major context (or as a secondary dominant) and i64 in minor contexts.
- bug fixes on rounding approximate durations (such as in MIDI parsing)
converter.parse('tinyNotation: ...', raiseExceptions=True) allows tinyNotation to bubble up anything that prevents reading a token. off by default, but useful for debugging. Expect this keyword to start appearing (w/ default False) for other conversion methods.
- Changed: as promised years ago, the default on Stream.recurse() is now NOT to include the caller itself in recursion. Use keyword argument "includeSelf=True" to do so. Recurse keywords are keyword only.
- Changed: arguments to Music21Object.contextSites are keyword only. This fixes a few little bugs. Same with Stream.elementsChanged()
- MusicXML stores Fingerings properly (thanks @hofst !)
- Fixes for extreme pitchbends (very close to wheel minimum) on MIDI.
- Dropped bug-fixes for very old versions of Sibelius and MuseScore < 2.0
- Added bug catching for MusicXML that gives the shape of the clef ('G', 'F') but no line -- uses sensible defaults. And many other cases in MusicXML where an attribute is empty (as one musicxml writer is now producing)
As always thanks to MIT, the Seaver Institute, and the NEH for funding early development of
Upgrade with “pip install --upgrade music21”
music21 v.5 is PYTHON 3 ONLY
Do not upgrade to this version if you are using Python 2.7 (or better still, upgrade yourself to Python 3.6 instead). It runs on Python 3.4-3.6 only.
music21 v.4 is the last version to support Python 2.
run "pip3 install music21" to install.
music21 v.5 brings with it seven months of determined work by an open-source team to streamline music analysis. The move to Python 3 allowed us to greatly simplify the codebase and to speed up many commonly used features in
music21. If you are apprehensive about switching to Python 3, I hope you'll be convinced that it is worth it the first time you run
chordify() on a large score v.5. and see that what might have taken an hour can now be done in few seconds. A great number of bugs involving working with non-English text have been fixed.
As a new major release,
music21 breaks backwards compatibility where necessary and deprecates underused functions and things that can be done better in other ways. We're always trying to balance bringing new features with keeping the software as simple to use as possible.
Python 3 only. Yes, I said that but I'm saying it again. This change has made developing much faster and a lot more fun. Also it's made music21 more powerful and faster.
Chordify moves from O(n^2) to O(n) time -- Chordify on large scores works great now.
MusicXML roundtrip now preserves much about appearance, style, metadata, etc. -- you can now load a musicxml file into music21 and back into your software and 90% of the time you'll get visually the same result as the original software. Finale roundtrip is especially good!
Corpora searching is much better and much faster. Metadata is stored in pickle format.
Feature Extraction runs multicore by default. Together with the average of 10x faster chordify, feature extraction on large datasets on multicore systems is now very strong. Parallel processing is easier and much better documented.
Features with JSymbolic equivalents much more closely match the spec and new features have been added (thanks Micah Walter!)
Many routines that used to return string filepaths now return pathlib.Path objects. Especially useful for people running on Python 3.6
Almost all functions deprecated in v. 4 have been removed.
Many keyword functions now require the keyword, so instead of
makeNotation(inPlace=True), since explicit is better than implicit, this is a good way of being sure that only the right arguments are being changed.
parsing of Volpiano (Gregorian chant notation) added.
RehearsalMarks are now supported internally and in MusicXML reading/writing.
Other musicXML improvements: Volume of individual notes is now imported and exported. Glissandi and barlines and transposition work better. More elements can be hidden. Empty spaces in MusicXML measures are converted to hidden rests, to avoid gapped streams. Pitches in chords on musicxml import are always sorted from lowest to highest. Fretboard diagrams are supported and Instrument objects have the MusicXML v. 3 sound tags attached. (thanks to Luke Poeppel for these last two)
Corpora improvments: works by Amy Beach, Schubert (Lindebaum), better Bach Chorales (thanks Dr. Norman Schmidt), and Scott Joplin. Errors in various pieces fixed.
Scales and IntervalNetworks run much faster and are better documented.
voiceLeading.VoiceLeadingQuartet improved. compatibility change: improperResolution renamed to isProperResolution and improved. Former title implied that False meant it was proper; now the title reflects the output. Many other fixes and improvements thanks to Ryaan Ahmed.
analysis.transposition -- searches pitch lists for number of distinct transpositions; neoriemannian analysis improvements (thanks to Mark Gotham for both) Stream alignment tools in alpha.analysis (thanks to Emily Zhang)
Copyright and other metadata is preserved in many formats on import. This is just being a good neighbor.
Demos and most alpha code has been moved to a new separate repository: https://github.com/cuthbertLab/music21-demos
-- they will be updated much less frequently. This will also make code development faster. Thanks to all who have contributed to music21's development. We'll be able to get more demos into the codebase by not needing to update them at every moment.
Bugs fixed: chords not in voices in measures with voices were not found in some routines. Instrument objects without midiProgram explicitly set get a program on MIDI output. MIDI no longer inserts a rest at the beginning (thanks KKONZ). Chord.normalOrder fixed (thanks luiselroquero), bugs in Capella parsing. Bugs related to Apple File System High Sierra not sorting files by default. Accented braille characters are exported properly.
Docs can be downloaded as a separate zip file.
I have no major backward-incompatable plans for the near future, so I expect v.5 to have a longer life than the last few releases (at least 18 months, and possibly 2-3 years), but work will continue on smaller subreleases to come. Thanks again to MIT, School of Humanities, Arts, and Social Sciences, and the Music and Theater Arts section for their support of
music21 and the Seaver Institute and the National Endowment for the Humanities for financial support.
The first and hopefully only beta/release candidate of music21 v. 5 has been released. If no bugs are discovered/reported, I expect this to be the release version to be released next weekend and I’m going to hold off on merging any new pull requests until then. I expect v.5 of music21 to have a longer than usual lifespan (at least 18 months, possibly more) and don’t have any backwards incompatible changes planned for the future except in the alpha and tree directories.
Music21 v.5 is the first version to require Python 3 (3.4 required. 3.5 or 3.6 recommended as this will be the last version to support 3.4).
Changes since Alpha 2:
- braille -- accented characters translate to braille
- features -- many jSymbolic Feature Extractors match the spec more closely (thanks to Micah W. for the patches). Expect more of these improvements throughout the v.5 lifecycle.
- Bach chorales -- improvements to naming and texts. Expect more of these improvements throughout v.5. Thank you to Dr. Norman Schmidt for these.
- Improvements and fixes in voiceleading.py -- thanks to Ryaan Ahmed
- More objects can be hidden with "hideObjectOnPrint"
- Joplin, Maple Leaf Rag added to corpus
- Guitar and other fretboards supported. Thanks to Luke Poeppel
- Improvements to IPython/music21j MIDI
- Added stream alignment tools in alpha.analysis. Thanks to Emily Zhang
- docs for Stream.insertAndShift improved greatly.
- separate zip file for docs.
The second alpha release of music21 version 5 (Python 3.4+ only) has been released. There have been 47 new commits since alpha 1 (more on that below) mostly of a maintenance sort. V5 is still pre-release code, and the syntax is still in flux until the main release next summer, but it is well-tested and good for most hobbyist coding.
Here are the main changes since alpha 1:
I neglected to post on this forum the announcement of music21 v.5 alpha 1, so the many great improvements there are listed below, with a new installation link:--
- Better parallel processing system (esp. in terms of docs)
- Pitches are 30% faster to create, notes are 15% faster. You do create notes, don't you? :-)
- Better musicxml support: volume. Improvements to transposition, glissando, barlines
- Corpus: added works by Amy Beach, Schubert (Lindenbaum), fixed missing Bach Chorales (thanks Dr. Schmidt!) and error in Haydn op. 1 no. 1 movement 1(thanks Joshua Ballance)
- Scales, IntervalNetwork: faster and better documented.
- NeoRiemannian analysis greatly improved (thanks Mark Gotham!)
- voiceLeading.VoiceLeadingQuartet improved. compatibility change: improperResolution renamed to isProperResolution and improved. Former title implied that False meant it was proper; now the title reflects the output.
- Instrument objects now have their MusicXML v.3 sound tags attached (thanks Luke P.!)
- Bugs fixed: chords not in voices in measures with voices were not found in some routines. Instrument objects without midiProgram explicitly set get a program on MIDI output. MIDI no longer inserts a rest at the beginning (thanks KKONZ). Chord.normalOrder fixed (thanks ), bugs in Capella parsing. Bugs related to Apple File System High Sierra not sorting files by default.
Alpha 1 of v.5 of music21 includes an amazingly faster improved version of Chordify (thanks in large part to work by Josiah Wolf Oberholtzer)
music21 v.5 is PYTHON 3 ONLY
Do not upgrade to this version if you are using Python 2.7 (or better still, upgrade yourself to Python 3.6 instead). It runs on Python 3.4-3.6 only.
This is alpha code -- I am still formulating the changes for m21 version 5. Some things that have disappeared since v.4 may reappear, but some things that are currently here may be gone or significantly changed by v5 release. YMMV.
Other big changes:
- Python 3 only. Yes, I said that but I'm saying it again. This change has made developing much faster and a lot more fun. Also it's made music21 more powerful and faster.
- Chordify moves from O(n^2) to O(n) time -- Chordify on large scores works great now.
- MusicXML roundtrip now preserves much about appearance, style, metadata, etc. -- you can now load a musicxml file into music21 and back into your software and 90% of the time you'll get visually the same result as the original software. Finale roundtrip is especially good!
- Corpora searching is much better and much faster. Metadata is stored in pickle format.
- Feature Extraction runs multicore by default. Together with the average of 10x faster chordify, feature extraction on large datasets on multicore systems is now very strong.
- Many routines that used to return string filepaths now return pathlib.Path objects.
- Almost all deprecated functions are removed.
- Many keyword functions are now keyword only, so no worries about passing in "inPlace" accidentally.
- parsing of Volpiano (Gregorian chant notation) added.
- RehearsalMark is added (and in musicxml also).
- Empty spaces in MusicXML measures are converted to hidden rests, to avoid gapped streams.
- Pitches in chords on musicxml import are always sorted from lowest to highest.
- analysis.transposition -- searches pitch lists for number of distinct transpositions (thanks Mark Gotham)
- Copyright and other metadata is preserved in many formats on import. This is just being a good neighbor.
- Demos and most alpha code has been moved to a new separate repository: https://github.com/cuthbertLab/music21-demos -- they will be updated much less frequently. This will also make code development faster. Thanks to all who have contributed to music21's development. We'll be able to get more demos into the codebase by not needing to update them at every moment.
The remarkable work over less than a month has been largely aided by dropping the Python 2 code dependencies, so while upgrading to Python 3.6 might cause some grumbling, my ability to forge ahead quickly I hope will more than make up for it!
This is alpha code. It won't install by default on pip. Use
pip3 install --upgrade music21==5.0.5a2
How can I contribute?
Music21 is a rapidly-progressing project,
but it is always looking for researchers interested
in contributing code, questions, freely-distributable pieces, bug
fixes, or documentation. Please
contact Michael Scott
Cuthbert (cuthbert at mit.edu), Principal Investigator.
The development of music21 has been
supported by the School of
Humanities, Arts, and Social Sciences
and Theater Arts section, and
generous grants from the Seaver Institute and the
NEH/Digging-Into-Data Challenge. Further donations to the project are always welcome.