# Melodies and MIDI Notes

This module describes how to transform a melody into a sequence of MIDI notes using music21.

There are many instances in computational analysis when it is useful to represent notes as numeric values. For example, using numbers can be useful for music theoretical analysis, and for performing mathematical operations, such as those common to post-tonal analysis. (You must install music21 before running this module.)

MIDI note numbers are a widely-used numeric representation of musical pitch. MIDI note numbers span the range 0-127, from the C nearly two octaves below the lowest note on the piano (0) to the G about an octave and a half above the highest note on the piano (127). The range of standard, 88-key piano is 21-108; middle C is 60. (See a conversion table here.)

If you are using material from an existing work, first you must extract the individual part, melody, or passage that you would like to transcribe as a sequence of MIDI notes.

The variable my_melody will represent our melody. First, let’s view the sequence of pitches by using a for loop:

``````for x in my_melody.pitches:
print(x)``````

This will output a list of pitches using the conventional letter labeling scheme. We can convert each pitch to a MIDI note number by using the midi property:

``````for x in my_melody.pitches:
print(x.midi)``````

We can use a list comprehension to generate a new list of MIDI note numbers:

``````midi_only = [x.midi for x in my_melody.pitches]

midi_only
> [71, 71, 70, 68, 66, 71, 73, 74, 74, 76, 74, 73, 73, 74]``````

When you represent the pitches of a melody as a list of integers, you gain access to a broader palette of mathematical tools in Python. At the same time, it’s important to acknowledge what is lost at this level of abstraction: things like rhythms, timbre, and dynamics. Consequently, the extent to which it is helpful or appropriate to work with abstract representations such as this depends on your research goals.

For more on working with pitches in music21, see this page.