Music21: Extracting Notes and Durations

Music21: Getting All Notes with Durations

Music21 is a powerful Python library for music analysis and manipulation. This article explores how to extract all notes and their corresponding durations from a music score using Music21.

Working with a Music21 Score

1. Importing Music21 and Creating a Score

  from music21 import * score = converter.parse("your_music_file.xml")  

Replace “your_music_file.xml” with the actual path to your MIDI or XML file.

2. Retrieving Notes

  notes = score.flat.notes  

This line uses flat.notes to flatten the score into a single stream and obtain all notes within it.

3. Iterating and Extracting Information

  for note in notes: print(f"Note: {note.nameWithOctave}, Duration: {note.duration.quarterLength}")  

The code iterates through the notes, printing the note name with octave and its duration in quarter lengths.

Example Output

Let’s imagine you have a simple melody with the following notes:

Note Duration
C4 1/4
D4 1/2
E4 1/4

Running the Music21 code on this melody would produce output like this:

  Note: C4, Duration: 1.0 Note: D4, Duration: 2.0 Note: E4, Duration: 1.0  

Key Points

  • The duration.quarterLength attribute provides the duration in terms of quarter notes.
  • Music21 supports various music formats (MIDI, XML, etc.).
  • The flat.notes method streamlines note extraction by handling complex structures.

By combining Music21’s functionalities, you can efficiently retrieve and analyze notes and their durations, paving the way for advanced music analysis and processing tasks.

Leave a Reply

Your email address will not be published. Required fields are marked *