music21.instrument

This module represents instruments through objects that contain general information such as Metadata for instrument names, classifications, transpositions and default MIDI program numbers. It also contains information specific to each instrument or instrument family, such as string pitches, etc. Information about instrumental ensembles is also included here though it may later be separated out into its own ensemble.py module.

Instrument

class music21.instrument.Instrument(instrumentName=None)

Base class for all musical instruments. Designed for subclassing, though usually a more specific instrument class (such as StringInstrument) would be better to subclass.

Some defined attributes for instruments include:

  • partId

  • partName

  • partAbbreviation

  • instrumentId

  • instrumentName

  • instrumentAbbreviation

  • midiProgram (0-indexed)

  • midiChannel (0-indexed)

  • lowestNote (a note object or a string for _written_ pitch)

  • highestNote (a note object or a string for _written_ pitch)

  • transposition (an interval object)

  • inGMPercMap (bool – if it uses the GM percussion map)

  • soundfontFn (filepath to a sound font, optional)

Instrument bases

Instrument read-only properties

Read-only properties inherited from Music21Object:

Read-only properties inherited from ProtoM21Object:

Instrument read/write properties

Read/write properties inherited from Music21Object:

Instrument methods

Instrument.autoAssignMidiChannel(usedChannels=[])

Assign an unused midi channel given a list of used channels.

assigns the number to self.midiChannel and returns it as an int.

Note that midi channel 10 (9 in music21) is special, and thus is skipped.

Currently only 16 channels are used.

Note that the reused “usedChannels=[]” in the signature is NOT a mistake, but necessary for the case where there needs to be a global list.

>>> used = [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11]
>>> i = instrument.Violin()
>>> i.autoAssignMidiChannel(used)
12
>>> i.midiChannel
12

Unpitched percussion will be set to 9, so long as it’s not in the filter list:

>>> used = [0]
>>> i = instrument.Maracas()
>>> i.autoAssignMidiChannel(used)
9
>>> i.midiChannel
9
>>> used = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> i = instrument.Woodblock()
>>> i.autoAssignMidiChannel(used)
11
>>> i.midiChannel
11
Instrument.bestName()

Find a viable name, looking first at instrument, then part, then abbreviations.

Instrument.instrumentIdRandomize()

Force a unique id by using an MD5

Instrument.partIdRandomize()

Force a unique id by using an MD5

Methods inherited from Music21Object:

Methods inherited from ProtoM21Object:

Instrument instance variables

Instance variables inherited from Music21Object:

Contrabass

class music21.instrument.Contrabass

For the Contrabass (or double bass), the stringPitches attribute refers to the sounding pitches of each string; whereas the lowestNote attribute refers to the lowest written note.

Contrabass bases

Contrabass read-only properties

Read-only properties inherited from Music21Object:

Read-only properties inherited from ProtoM21Object:

Contrabass read/write properties

Read/write properties inherited from StringInstrument:

Read/write properties inherited from Music21Object:

Contrabass methods

Methods inherited from Instrument:

Methods inherited from Music21Object:

Methods inherited from ProtoM21Object:

Contrabass instance variables

Instance variables inherited from Music21Object:

StringInstrument

class music21.instrument.StringInstrument

StringInstrument bases

StringInstrument read-only properties

Read-only properties inherited from Music21Object:

Read-only properties inherited from ProtoM21Object:

StringInstrument read/write properties

StringInstrument.stringPitches

stringPitches is a property that stores a list of Pitches (or pitch names, such as “C4”) that represent the pitch of the open strings from lowest to highest.[*]

>>> vln1 = instrument.Violin()
>>> [str(p) for p in vln1.stringPitches]
['G3', 'D4', 'A4', 'E5']

instrument.stringPitches are full pitch objects, not just names:

>>> [x.octave for x in vln1.stringPitches]
[3, 4, 4, 5]

Scordatura for Scelsi’s violin concerto Anahit. (N.B. that string to pitch conversion is happening automatically)

>>> vln1.stringPitches = ['G3', 'G4', 'B4', 'D4']

([*]In some tuning methods such as reentrant tuning on the ukulele, lute, or five-string banjo the order might not strictly be from lowest to highest. The same would hold true for certain violin scordatura pieces, such as some of Biber’s *Mystery Sonatas*)

Read/write properties inherited from Music21Object:

StringInstrument methods

Methods inherited from Instrument:

Methods inherited from Music21Object:

Methods inherited from ProtoM21Object:

StringInstrument instance variables

Instance variables inherited from Music21Object:

UnpitchedPercussion

class music21.instrument.UnpitchedPercussion

UnpitchedPercussion bases

UnpitchedPercussion read-only properties

Read-only properties inherited from Music21Object:

Read-only properties inherited from ProtoM21Object:

UnpitchedPercussion read/write properties

UnpitchedPercussion.modifier

Returns or sets the modifier for this instrument. A modifier could be something like “low-floor” for a TomTom or “rimshot” for a SnareDrum.

If the modifier is in the object’s ._modifierToPercMapPitch dictionary then changing the modifier also changes the .percMapPitch for the object

>>> bd = instrument.BongoDrums()
>>> bd.modifier
'high'
>>> bd.percMapPitch
60
>>> bd.modifier = 'low'
>>> bd.percMapPitch
61

Variations on modifiers can also be used and they get normalized:

>>> wb1 = instrument.Woodblock()
>>> wb1.percMapPitch
76
>>> wb1.modifier = 'LO'
>>> wb1.percMapPitch
77
>>> wb1.modifier  # n.b. -- not LO
'low'

Read/write properties inherited from Music21Object:

UnpitchedPercussion methods

Methods inherited from Instrument:

Methods inherited from Music21Object:

Methods inherited from ProtoM21Object:

UnpitchedPercussion instance variables

Instance variables inherited from Music21Object:

Functions

music21.instrument.bundleInstruments(streamIn: music21.stream.base.Stream, *, inPlace=False) → Optional[music21.stream.base.Stream]
>>> up1 = note.Unpitched()
>>> up1.storedInstrument = instrument.BassDrum()
>>> upUnknownInstrument = note.Unpitched()
>>> up2 = note.Unpitched()
>>> up2.storedInstrument = instrument.Cowbell()
>>> s = stream.Stream()
>>> s.append(up1)
>>> s.append(upUnknownInstrument)
>>> s.append(up2)
>>> s2 = instrument.unbundleInstruments(s)
>>> s3 = instrument.bundleInstruments(s2)
>>> for test in s3:
...     print(test.storedInstrument)
Bass Drum
Bass Drum
Cowbell
music21.instrument.deduplicate(s: music21.stream.base.Stream, inPlace: bool = False) → music21.stream.base.Stream

Check every offset in s for multiple instrument instances. If the .partName can be standardized across instances, i.e. if each instance has the same value or None, and likewise for .instrumentName, standardize the attributes. Further, and only if the above conditions are met, if there are two instances of the same class, remove all but one; if at least one generic Instrument instance is found at the same offset as one or more specific instruments, remove the generic Instrument instances.

Two Instrument instances:

>>> i1 = instrument.Instrument(instrumentName='Semi-Hollow Body')
>>> i2 = instrument.Instrument()
>>> i2.partName = 'Electric Guitar'
>>> s1 = stream.Stream()
>>> s1.insert(4, i1)
>>> s1.insert(4, i2)
>>> list(s1.getInstruments())
[<music21.instrument.Instrument 'Semi-Hollow Body'>,
    <music21.instrument.Instrument 'Electric Guitar: '>]
>>> post = instrument.deduplicate(s1)
>>> list(post.getInstruments())
[<music21.instrument.Instrument 'Electric Guitar: Semi-Hollow Body'>]

One Instrument instance and one subclass instance, with inPlace and parts:

>>> from music21.stream import Score, Part
>>> i3 = instrument.Instrument()
>>> i3.partName = 'Piccolo'
>>> i4 = instrument.Piccolo()
>>> s2 = stream.Score()
>>> p1 = stream.Part()
>>> p1.append([i3, i4])
>>> p2 = stream.Part()
>>> p2.append([instrument.Flute(), instrument.Flute()])
>>> s2.insert(0, p1)
>>> s2.insert(0, p2)
>>> list(p1.getInstruments())
[<music21.instrument.Instrument 'Piccolo: '>, <music21.instrument.Piccolo 'Piccolo'>]
>>> list(p2.getInstruments())
[<music21.instrument.Flute 'Flute'>, <music21.instrument.Flute 'Flute'>]
>>> s2 = instrument.deduplicate(s2, inPlace=True)
>>> list(p1.getInstruments())
[<music21.instrument.Piccolo 'Piccolo: Piccolo'>]
>>> list(p2.getInstruments())
[<music21.instrument.Flute 'Flute'>]
music21.instrument.ensembleNameBySize(number)

return the name of a generic ensemble with “number” players:

>>> instrument.ensembleNameBySize(4)
'quartet'
>>> instrument.ensembleNameBySize(1)
'solo'
>>> instrument.ensembleNameBySize(83)
'treoctogetet'
music21.instrument.fromString(instrumentString)

Given a string with instrument content (from an orchestral score for example), attempts to return an appropriate Instrument.

>>> from music21 import instrument
>>> t1 = instrument.fromString('Clarinet 2 in A')
>>> t1
<music21.instrument.Clarinet 'Clarinet 2 in A'>
>>> t1.transposition
<music21.interval.Interval m-3>
>>> t2 = instrument.fromString('Clarinetto 3')
>>> t2
<music21.instrument.Clarinet 'Clarinetto 3'>
>>> t3 = instrument.fromString('flauto 2')
>>> t3
<music21.instrument.Flute 'flauto 2'>

Excess information is ignored, and the useful information can be extracted correctly as long as it’s sequential.

>>> t4 = instrument.fromString('I <3 music saxofono tenore go beavers')
>>> t4
<music21.instrument.TenorSaxophone 'I <3 music saxofono tenore go beavers'>

Some more demos:

>>> t5 = instrument.fromString('Bb Clarinet')
>>> t5
<music21.instrument.Clarinet 'Bb Clarinet'>
>>> t5.transposition
<music21.interval.Interval M-2>
>>> t6 = instrument.fromString('Clarinet in B-flat')
>>> t5.__class__ == t6.__class__
True
>>> t5.transposition == t6.transposition
True
>>> t7 = instrument.fromString('B-flat Clarinet.')
>>> t5.__class__ == t7.__class__ and t5.transposition == t7.transposition
True
>>> t8 = instrument.fromString('Eb Clarinet')
>>> t5.__class__ == t8.__class__
True
>>> t8.transposition
<music21.interval.Interval m3>

Note that because of the ubiquity of B-flat clarinets and trumpets, and the rareness of B-natural forms of those instruments, this gives a B-flat, not B-natural clarinet, using the German form:

>>> t9 = instrument.fromString('Klarinette in B.')
>>> t9
<music21.instrument.Clarinet 'Klarinette in B.'>
>>> t9.transposition
<music21.interval.Interval M-2>

Use “H” or “b-natural” to get an instrument in B-major. Or donate one to me and I’ll change this back!

Finally, standard abbreviations are acceptable:

>>> t10 = instrument.fromString('Cl in B-flat')
>>> t10
<music21.instrument.Clarinet 'Cl in B-flat'>
>>> t10.transposition
<music21.interval.Interval M-2>

This should work with or without a terminal period (for both ‘Cl’ and ‘Cl.’):

>>> t11 = instrument.fromString('Cl. in B-flat')
>>> t11.__class__ == t10.__class__
True

Previously an exact instrument name was not always working:

>>> instrument.fromString('Flute')
<music21.instrument.Flute 'Flute'>

This common MIDI instrument was not previously working:

>>> instrument.fromString('Choir (Aahs)')
<music21.instrument.Choir 'Choir (Aahs)'>
music21.instrument.instrumentFromMidiProgram(number: int) → music21.instrument.Instrument

Return the instrument with “number” as its assigned MIDI program. Notice any of the values 0-5 will return Piano.

Lookups are performed against instrument.MIDI_PROGRAM_TO_INSTRUMENT.

>>> instrument.instrumentFromMidiProgram(4)
<music21.instrument.ElectricPiano 'Electric Piano'>
>>> instrument.instrumentFromMidiProgram(21)
<music21.instrument.Accordion 'Accordion'>
>>> instrument.instrumentFromMidiProgram(500)
Traceback (most recent call last):
music21.exceptions21.InstrumentException: No instrument found for MIDI program 500
>>> instrument.instrumentFromMidiProgram('43')
Traceback (most recent call last):
TypeError: Expected int, got <class 'str'>
music21.instrument.partitionByInstrument(streamObj)

Given a single Stream, or a Score or similar multi-part structure, partition into a Part for each unique Instrument, joining events possibly from different parts.

>>> p1 = converter.parse("tinynotation: 4/4 c4  d  e  f  g  a  b  c'  c1")
>>> p2 = converter.parse("tinynotation: 4/4 C#4 D# E# F# G# A# B# c#  C#1")
>>> p1.getElementsByClass('Measure')[0].insert(0.0, instrument.Piccolo())
>>> p1.getElementsByClass('Measure')[0].insert(2.0, instrument.AltoSaxophone())
>>> p1.getElementsByClass('Measure')[1].insert(3.0, instrument.Piccolo())
>>> p2.getElementsByClass('Measure')[0].insert(0.0, instrument.Trombone())
>>> p2.getElementsByClass('Measure')[0].insert(3.0, instrument.Piccolo())  # not likely...
>>> p2.getElementsByClass('Measure')[1].insert(1.0, instrument.Trombone())
>>> s = stream.Score()
>>> s.insert(0, p1)
>>> s.insert(0, p2)
>>> s.show('text')
{0.0} <music21.stream.Part ...>
    {0.0} <music21.stream.Measure 1 offset=0.0>
        {0.0} <music21.instrument.Piccolo 'Piccolo'>
        {0.0} <music21.clef.TrebleClef>
        {0.0} <music21.meter.TimeSignature 4/4>
        {0.0} <music21.note.Note C>
        {1.0} <music21.note.Note D>
        {2.0} <music21.instrument.AltoSaxophone 'Alto Saxophone'>
        {2.0} <music21.note.Note E>
        {3.0} <music21.note.Note F>
    {4.0} <music21.stream.Measure 2 offset=4.0>
        {0.0} <music21.note.Note G>
        {1.0} <music21.note.Note A>
        {2.0} <music21.note.Note B>
        {3.0} <music21.instrument.Piccolo 'Piccolo'>
        {3.0} <music21.note.Note C>
    {8.0} <music21.stream.Measure 3 offset=8.0>
        {0.0} <music21.note.Note C>
        {4.0} <music21.bar.Barline type=final>
{0.0} <music21.stream.Part ...>
    {0.0} <music21.stream.Measure 1 offset=0.0>
        {0.0} <music21.instrument.Trombone 'Trombone'>
        {0.0} <music21.clef.BassClef>
        {0.0} <music21.meter.TimeSignature 4/4>
        {0.0} <music21.note.Note C#>
        {1.0} <music21.note.Note D#>
        {2.0} <music21.note.Note E#>
        {3.0} <music21.instrument.Piccolo 'Piccolo'>
        {3.0} <music21.note.Note F#>
    {4.0} <music21.stream.Measure 2 offset=4.0>
        {0.0} <music21.note.Note G#>
        {1.0} <music21.instrument.Trombone 'Trombone'>
        {1.0} <music21.note.Note A#>
        {2.0} <music21.note.Note B#>
        {3.0} <music21.note.Note C#>
    {8.0} <music21.stream.Measure 3 offset=8.0>
        {0.0} <music21.note.Note C#>
        {4.0} <music21.bar.Barline type=final>
>>> s2 = instrument.partitionByInstrument(s)
>>> len(s2.parts)
3

# TODO: this step might not be necessary… >>> for p in s2.parts: … p.makeRests(fillGaps=True, inPlace=True)

# TODO: this step SHOULD not be necessary (.template())…

>>> for p in s2.parts:
...     p.makeMeasures(inPlace=True)
...     p.makeTies(inPlace=True)
>>> s2.show('text')
{0.0} <music21.stream.Part Piccolo>
    {0.0} <music21.stream.Measure 1 offset=0.0>
        {0.0} <music21.instrument.Piccolo 'Piccolo'>
        {0.0} <music21.clef.TrebleClef>
        {0.0} <music21.meter.TimeSignature 4/4>
        {0.0} <music21.note.Note C>
        {1.0} <music21.note.Note D>
        {2.0} <music21.note.Rest quarter>
        {3.0} <music21.note.Note F#>
    {4.0} <music21.stream.Measure 2 offset=4.0>
        {0.0} <music21.note.Note G#>
        {1.0} <music21.note.Rest half>
        {3.0} <music21.note.Note C>
    {8.0} <music21.stream.Measure 3 offset=8.0>
        {0.0} <music21.note.Note C>
        {4.0} <music21.bar.Barline type=final>
{0.0} <music21.stream.Part Alto Saxophone>
    {0.0} <music21.stream.Measure 1 offset=0.0>
        {0.0} <music21.instrument.AltoSaxophone 'Alto Saxophone'>
        {0.0} <music21.clef.TrebleClef>
        {0.0} <music21.meter.TimeSignature 4/4>
        {0.0} <music21.note.Rest half>
        {2.0} <music21.note.Note E>
        {3.0} <music21.note.Note F>
    {4.0} <music21.stream.Measure 2 offset=4.0>
        {0.0} <music21.note.Note G>
        {1.0} <music21.note.Note A>
        {2.0} <music21.note.Note B>
        {3.0} <music21.bar.Barline type=final>
{0.0} <music21.stream.Part Trombone>
    {0.0} <music21.stream.Measure 1 offset=0.0>
        {0.0} <music21.instrument.Trombone 'Trombone'>
        {0.0} <music21.clef.BassClef>
        {0.0} <music21.meter.TimeSignature 4/4>
        {0.0} <music21.note.Note C#>
        {1.0} <music21.note.Note D#>
        {2.0} <music21.note.Note E#>
        {3.0} <music21.note.Rest quarter>
    {4.0} <music21.stream.Measure 2 offset=4.0>
        {0.0} <music21.note.Rest quarter>
        {1.0} <music21.note.Note A#>
        {2.0} <music21.note.Note B#>
        {3.0} <music21.note.Note C#>
    {8.0} <music21.stream.Measure 3 offset=8.0>
        {0.0} <music21.note.Note C#>
        {4.0} <music21.bar.Barline type=final>

TODO: parts should be in Score Order. Coincidence that this almost works. TODO: use proper recursion to make a copy of the stream. TODO: final barlines should be aligned.

music21.instrument.unbundleInstruments(streamIn: StreamType, *, inPlace=False) → Optional[StreamType]

takes a Stream that has NotRest objects and moves their .storedInstrument attributes to a new Stream (unless inPlace=True)

>>> up1 = note.Unpitched()
>>> up1.storedInstrument = instrument.BassDrum()
>>> up2 = note.Unpitched()
>>> up2.storedInstrument = instrument.Cowbell()
>>> s = stream.Stream()
>>> s.append(up1)
>>> s.append(up2)
>>> s2 = instrument.unbundleInstruments(s)
>>> s2.show('text')
{0.0} <music21.instrument.BassDrum 'Bass Drum'>
{0.0} <music21.note.Unpitched object at 0x...>
{1.0} <music21.instrument.Cowbell 'Cowbell'>
{1.0} <music21.note.Unpitched object at 0x...>