Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Music21 Getting All notes with Durations

Im trying to get all notes with their durations(measures).

from music21 import *

allBach = corpus.search('bach')

x = allBach[0]
p = x.parse()

partStream = p.parts.stream()

for n in p.pitches:
    print "Pitch: " + str(n)

print "*************"

for n in p.notes:
    print "Note: " + str(n)
#print "Duration " + str(x.parse().duration)

Above code produces following output

Pitch: E5
Pitch: G5
Pitch: A5
Pitch: D5
Pitch: F#5
Pitch: A5
Pitch: D5
Pitch: F#5
Pitch: A5
Pitch: C6
Pitch: G4
Pitch: B4
Pitch: D5
*************

I know that pitch is a just name of the note with its octave, but Im trying to get note values with its durations(measures).

Also if you can help me on this, could you also explain why p.notes returns nothing. Thank you.

like image 896
Nerzid Avatar asked Apr 15 '16 12:04

Nerzid


1 Answers

Here's a version of your script that does what you want:

from music21 import *

allBach = corpus.search('bach')

x = allBach[0]
p = x.parse()

partStream = p.parts.stream()

for n in p.flat.notes:
    print "Note: %s%d %0.1f" % (n.pitch.name, n.pitch.octave, n.duration.quarterLength)

The main thing you got caught out by was the behaviour of the .notes property on Stream objects. music21 implements a hierarchical structure of containers including: Scores, Parts, and Measures. Most of the iterating read-only properties (including .notes) respect that hierarchy by not arbitrarily descending it. music21 then provides the read-only property .flat to flatten that hierarchy into just the leaf-type objects (notes and rests).

The object you got back from your call to p.parts.stream() was a Score object and so asking directly for its .notes resulted in an empty iterator as there were no Notes which were direct children of that Score. But using .flat.notes flattens the hierarchy and so gives you direct access to the Notes.

In the solution, also notice that I've accessed the .pitch.name, .pitch.octave and .duration.quarterLength values directly rather than just asking for the str representation of a Note object.

In your question you seem to be conflating the concepts "duration" and "measure". In music theory, duration is the time a note lasts for (often measured in beats) and "measure" is the (US English) name of a metrical division containing some number of beats (made of notes and/or rests) determined by the current time signature in operation. In notation, measures are delimited on the staff by vertical lines.

like image 177
ironchicken Avatar answered Nov 04 '22 11:11

ironchicken