VR_1312 VR_1312 - 1 year ago 69
Python Question

music21 - Transpose streams to a given key

Is there a function or easy way to transpose a stream to a given key?

I want to use it in a loop, e.g, take a set of major streams and transpose all of then to C major (so then I can do some statistical work with them).

All the transpose tools I saw work with intervals or number of tones, not fixed keys. It shouldn't be so hard to write my function, but I suppose that it has to be already done... Thanks

Answer Source

If s is a Stream (such as a Score or Part), then s.transpose('P4') will move it up a Perfect Fourth, etc. If you know the key of s as k major, then i = interval.Interval(k, 'C') will let you do s.transpose(i) to move from k to C. If you don't know the key of s, then k = s.analyze('key') will do a pretty decent job of figuring it out (using the Krumhansl probe-tone method). Putting it all together.

from music21 import *
for fn in filenameList:
    s = converter.parse(fn)
    k = s.analyze('key')
    i = interval.Interval(k.tonic, pitch.Pitch('C'))
    sNew = s.transpose(i)
    # do something with sNew

This assumes that your piece is likely to be in major. If not you can either treat it as the parallel major (f-minor -> F-major) or find in k.alternativeInterpretations the best major key analysis. Or transpose it to a minor if it's minor, etc.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download