Examples and Demonstrations

The following examples provide a few samples of some of the possibilities available when working with music21.

We start loading music21 like this:

from music21 import *

Searching the Corpus by Locale

This example searches all works in the corpus from two regions in China for the count and percentage of melodic sevenths. These works come from the Essen Folksong database, indexed and stored in the music21 corpus.

# Get an analysis tool
diversityTool = analysis.discrete.MelodicIntervalDiversity()

# get a list to store results.
results = []
# Iterate over two regions
for region in ('shanxi', 'fujian'):
    # Create storage units
    intervalDict = {}
    workCount = 0
    intervalCount = 0
    seventhCount = 0

    # Perform a location search on the corpus and iterate over
    # resulting file name and work number
    for result in corpus.search(region, field='locale'):
        workCount += 1

        # Parse the work and create a dictionary of intervals
        s = result.parse()
        intervalDict = diversityTool.countMelodicIntervals(s, found=intervalDict)

    # Iterate through all intervals, and count totals and sevenths
    for label in intervalDict.keys():
        intervalCount += intervalDict[label][1]
        if label in ['m7', 'M7']:
            seventhCount += intervalDict[label][1]

    # Calculate a percentage and store results
    pcentSevenths = round((seventhCount / float(intervalCount) * 100), 4)
    results.append((region, pcentSevenths, intervalCount, workCount))
# print results
for region, pcentSevenths, intervalCount, workCount in results:
    print('locale: {}: found {} percent melodic sevenths, '
          'out of {} intervals in {} works'.format(
              region, pcentSevenths, intervalCount, workCount))
 locale: shanxi: found 3.1994 percent melodic sevenths, out of 4282 intervals in 77 works
 locale: fujian: found 0.7654 percent melodic sevenths, out of 2613 intervals in 53 works

Pitch and Duration Transformations

This example creates a mensural canon from the Soprano part of a Bach chorale. The procedure extracts the Note objects from the parsed Score object, using the parse() function and the getElementById() method. Then, a new part Stream is created by first scaling the timing and duration of events with the augmentOrDiminish() method and then transposing the pitches with the transpose() method. The modified Stream is then inserted into another Stream and displayed with the show() method.

src = corpus.parse('bach/bwv323.xml')
soprano = src.getElementById('Soprano').recurse().notesAndRests.stream()
soprano.show()
../_images/devTest_unconvertedExamples_7_0.png
outputScore = stream.Score()

transformations = [(1.0, 'P1'),
                   (2.0, '-P5'),
                   (0.5, '-P11'),
                   (1.5, -24), # 24 semitones down
                  ]

for speed, transposition in transformations:
    part = soprano.augmentOrDiminish(speed)
    part.transpose(transposition, inPlace=True)
    outputScore.insert(0, part)

outputScore.measures(1, 5).show()
../_images/devTest_unconvertedExamples_8_0.png