Extracting Parts and Melodies

From Linewaves
Jump to navigation Jump to search

This module explains how to extract a part or melody from an existing piece of music.

Rather than manually entering all of the notes of a melody, we can import a musical work into music21 and then return the MIDI note numbers. We can import a work from a file, or from the web-based music21 corpus.

In this case, we’ll use a Bach chorale from the music21 corpus:

from music21 import *
my_work = corpus.parse('bach/bwv244.3')

If we want to view our notation, we can use the following code:

my_work.show()

The notation should appear in the MusicXML reader you specified during the music21 configuration process.

Most musical works, including Bach chorales, consist of more than one part, so we have to specify the part from which we want to extract the melody. We can use music21’s built-in parts property to do this, specifying the part with an index number as we would in a list.

This example pulls the first part from the work as a new variable (using index number 0):

first_part = my_work.parts[0]

If we know how the parts have been labeled, we can also access a part by name:

first_part = my_work.parts['Soprano']

(However, this is not generally recommended unless you know for certain how parts were labeled [i.e. you did it yourself]. Labels in digital corpora can exhibit irregularities of spelling and convention.)

We can view the excerpted part using the same method as above if we choose:

first_part.show()

Finally, if you want to focus on a particular passage within a part, you can specify the passage using the measures property. For example, this code redefines first_part as measures 1 through 4 of the melody:

first_part = first_part.measures(1, 4)

Once our melody is isolated as a variable, we can call it in various contexts to analyze it and apply different transformations and operations.