music21.abcFormat

ABC is a music format that, while being able to encode all sorts of scores, is especially strong at representing monophonic music, and folk music in particular.

Modules in the music21.abcFormat package deal with importing ABC into music21. Most people working with ABC data won’t need to use this package. To convert ABC from a file or URL to a Stream use the parse() function of the converter module:

>>> from music21 import *
>>> abcScore = converter.parse('/users/ariza/myScore.abc')

For users who will be editing ABC extensively or need a way to have music21 output ABC (which it doesn’t do natively), we suggest using the open source EasyABC package: https://www.nilsliberg.se/ksp/easyabc/ . You can set it up as a MusicXML reader through:

>>> us = environment.UserSettings()
>>> us['musicxmlPath'] = '/Applications/EasyABC.app'

or wherever you have downloaded EasyABC to (PC users might need: ‘c:/program files (x86)/easyabc/easyabc.exe’) (Thanks to Norman Schmidt for the heads up)

There is a two-step process in converting ABC files to Music21 Streams. First this module reads in the text-based .abc file and converts all the information into ABCToken objects. Then the function music21.abcFormat.translate.abcToStreamScore() of the music21.abcFormat.translate module translates those Tokens into music21 objects.

ABCFile

class music21.abcFormat.ABCFile(abcVersion=None)

ABC File or String access

The abcVersion attribution optionally specifies the (major, minor, patch) version of ABC to process– e.g., (1.2.0). If not set, default ABC 1.3 parsing is performed.

ABCFile bases

ABCFile read-only properties

Read-only properties inherited from ProtoM21Object:

ABCFile methods

ABCFile.close()
static ABCFile.extractReferenceNumber(strSrc: str, number: int) → str

Extract the string data relating to a single reference number from a file that defines multiple songs or pieces.

This method permits loading a single work from a collection/opus without parsing the entire file.

Here is sample data that is not correct ABC but demonstrates the basic concept:

>>> fileData = """
...   X:1
...   Hello
...   X:2
...   Aloha
...   X:3
...   Goodbye
...   """
>>> file2 = abcFormat.ABCFile.extractReferenceNumber(fileData, 2)
>>> print(file2)
X:2
Aloha

If the number does not exist, raises an ABCFileException:

>>> abcFormat.ABCFile.extractReferenceNumber(fileData, 99)
Traceback (most recent call last):
music21.abcFormat.ABCFileException: cannot find requested
    reference number in source file: 99

If the same number is defined twice in one file (should not be) only the first data is returned.

Changed in v6.2: now a static method.

ABCFile.open(filename)

Open a file for reading

ABCFile.openFileLike(fileLike)

Assign a file-like object, such as those provided by StringIO, as an open file object.

>>> from io import StringIO
>>> fileLikeOpen = StringIO()
ABCFile.read(number=None)

Read a file. Note that this calls readstr, which processes all tokens.

If number is given, a work number will be extracted if possible.

ABCFile.readstr(strSrc: str, number: Optional[int] = None)music21.abcFormat.ABCHandler

Read a string and process all Tokens. Returns a ABCHandler instance.

Methods inherited from ProtoM21Object:

ABCHandler

class music21.abcFormat.ABCHandler(abcVersion=None, lineBreaksDefinePhrases=False)

An ABCHandler is able to divide elements of a character stream into objects and handle store in a list, and passes global information to components

Optionally, specify the (major, minor, patch) version of ABC to process– e.g., (1.2.0). If not set, default ABC 1.3 parsing is performed.

If lineBreaksDefinePhrases is True then new lines within music elements define new phrases. This is useful for parsing extra information from the Essen Folksong repertory

New in v6.3 – lineBreaksDefinePhrases – does not yet do anything

ABCHandler methods

static ABCHandler.barlineTokenFilter(token: str) → List[music21.abcFormat.ABCBar]

Some single barline tokens are better replaced with two tokens. This method, given a token, returns a list of tokens. If there is no change necessary, the provided token will be returned in the list.

A staticmethod. Call on the class itself.

>>> abcFormat.ABCHandler.barlineTokenFilter('::')
[<music21.abcFormat.ABCBar ':|'>, <music21.abcFormat.ABCBar '|:'>]
>>> abcFormat.ABCHandler.barlineTokenFilter('|2')
[<music21.abcFormat.ABCBar '|'>, <music21.abcFormat.ABCBar '[2'>]
>>> abcFormat.ABCHandler.barlineTokenFilter(':|1')
[<music21.abcFormat.ABCBar ':|'>, <music21.abcFormat.ABCBar '[1'>]

If nothing matches, the original token is returned as an ABCBar object:

>>> abcFormat.ABCHandler.barlineTokenFilter('hi')
[<music21.abcFormat.ABCBar 'hi'>]
ABCHandler.definesMeasures()

Returns True if this token structure defines Measures in a normal Measure form. Otherwise False

>>> abcStr = ('M:6/8\nL:1/8\nK:G\nV:1 name="Whistle" ' +
...     'snm="wh"\nB3 A3 | G6 | B3 A3 | G6 ||\nV:2 name="violin" ' +
...     'snm="v"\nBdB AcA | GAG D3 | BdB AcA | GAG D6 ||\nV:3 name="Bass" ' +
...     'snm="b" clef=bass\nD3 D3 | D6 | D3 D3 | D6 ||')
>>> ah = abcFormat.ABCHandler()
>>> junk = ah.process(abcStr)
>>> ah.definesMeasures()
True
>>> abcStr = 'M:6/8\nL:1/8\nK:G\nB3 A3 G6 B3 A3 G6'
>>> ah = abcFormat.ABCHandler()
>>> junk = ah.process(abcStr)
>>> ah.definesMeasures()
False
ABCHandler.definesReferenceNumbers()

Return True if this token structure defines more than 1 reference number, usually implying multiple pieces encoded in one file.

>>> abcStr = 'X:5\nM:6/8\nL:1/8\nK:G\nB3 A3 | G6 | B3 A3 | G6 ||'
>>> ah = abcFormat.ABCHandler()
>>> junk = ah.process(abcStr)
>>> ah.definesReferenceNumbers()  # only one returns False
False
>>> abcStr = 'X:5\nM:6/8\nL:1/8\nK:G\nB3 A3 | G6 | B3 A3 | G6 ||\n'
>>> abcStr += 'X:6\nM:6/8\nL:1/8\nK:G\nB3 A3 | G6 | B3 A3 | G6 ||'
>>> ah = abcFormat.ABCHandler()
>>> junk = ah.process(abcStr)
>>> ah.definesReferenceNumbers()  # two tokens so returns True
True
ABCHandler.getReferenceNumber()

If tokens are processed, get the first reference number defined.

>>> abcStr = 'X:5\nM:6/8\nL:1/8\nK:G\nB3 A3 | G6 | B3 A3 | G6 ||'
>>> ah = abcFormat.ABCHandler()
>>> junk = ah.process(abcStr)
>>> ah.getReferenceNumber()
'5'
ABCHandler.getTitle() → Optional[str]

Get the first title tag. Used for testing.

Requires tokens to have been processed.

ABCHandler.hasNotes() → bool

If tokens are processed, return True if ABCNote or ABCChord classes are defined

>>> abcStr = 'M:6/8\nL:1/8\nK:G\n'
>>> ah1 = abcFormat.ABCHandler()
>>> junk = ah1.process(abcStr)
>>> ah1.hasNotes()
False
>>> abcStr = 'M:6/8\nL:1/8\nK:G\nc1D2'
>>> ah2 = abcFormat.ABCHandler()
>>> junk = ah2.process(abcStr)
>>> ah2.hasNotes()
True
ABCHandler.parseCommentForVersionInformation(commentLine: str)

If this is the first comment then searches for a version match and set it as .abcVersion

If not isFirstComment then does nothing:

>>> ah = abcFormat.ABCHandler()
>>> ah.abcVersion is None
True
>>> ah.isFirstComment
True
>>> ah.parseCommentForVersionInformation('%abc-2.3.2')
>>> ah.abcVersion
(2, 3, 2)
>>> ah.isFirstComment
False

Now will do nothing since isFirstComment is False

>>> ah.parseCommentForVersionInformation('%abc-4.9.7')
>>> ah.abcVersion
(2, 3, 2)
ABCHandler.process(strSrc: str) → None
ABCHandler.processComment()

Processes the comment at self.pos in self.strSrc, setting self.skipAhead, possibly self.abcVersion, and self.abcDirectives for the directiveKey.

TODO: store the comment in the stream also.

>>> from textwrap import dedent
>>> ah = abcFormat.ABCHandler()
>>> data = dedent("""
...    Hello % this is a comment
...    Bye
...    """)
>>> ah.strSrc = data
>>> ah.pos = 6
>>> ah.processComment()
>>> ah.skipAhead
19
>>> len(' this is a comment\n')
19
ABCHandler.splitByMeasure() → List[music21.abcFormat.ABCHandlerBar]

Divide a token list by Measures, also defining start and end bars of each Measure.

If a component does not have notes, leave as an empty bar. This is often done with leading metadata.

Returns a list of ABCHandlerBar instances. The first usually defines only Metadata

TODO: Test and examples

ABCHandler.splitByReferenceNumber()

Split tokens by reference numbers.

Returns a dictionary of ABCHandler instances, where the reference number is used to access the music. If no reference numbers are defined, the tune is available under the dictionary entry None.

>>> abcStr = 'X:5\nM:6/8\nL:1/8\nK:G\nB3 A3 | G6 | B3 A3 | G6 ||'
>>> abcStr += 'X:6\nM:6/8\nL:1/8\nK:G\nB3 A3 | G6 | B3 A3 | G6 ||'
>>> ah = abcFormat.ABCHandler()
>>> junk = ah.process(abcStr)
>>> len(ah)
28
>>> ahDict = ah.splitByReferenceNumber()
>>> 5 in ahDict
True
>>> 6 in ahDict
True
>>> 7 in ahDict
False

Each entry is its own ABCHandler object.

>>> ahDict[5]
<music21.abcFormat.ABCHandler object at 0x10b0cf5f8>
>>> len(ahDict[5].tokens)
14

Header information (except for comments) should be appended to all pieces.

>>> abcStrWHeader = '%abc-2.1\nO: Irish\n' + abcStr
>>> ah = abcFormat.ABCHandler()
>>> junk = ah.process(abcStrWHeader)
>>> len(ah)
29
>>> ahDict = ah.splitByReferenceNumber()
>>> 5 in ahDict
True
>>> 6 in ahDict
True
>>> 7 in ahDict
False

Did we get the origin header in each score?

>>> ahDict[5].tokens[0]
<music21.abcFormat.ABCMetadata 'O: Irish'>
>>> ahDict[6].tokens[0]
<music21.abcFormat.ABCMetadata 'O: Irish'>
ABCHandler.splitByVoice() → List[music21.abcFormat.ABCHandler]

Given a processed token list, look for voices. If voices exist, split into parts: common metadata, then next voice, next voice, etc.

Each part is returned as a ABCHandler instance.

>>> abcStr = ('M:6/8\nL:1/8\nK:G\nV:1 name="Whistle" ' +
...     'snm="wh"\nB3 A3 | G6 | B3 A3 | G6 ||\nV:2 name="violin" ' +
...     'snm="v"\nBdB AcA | GAG D3 | BdB AcA | GAG D6 ||\nV:3 name="Bass" ' +
...     'snm="b" clef=bass\nD3 D3 | D6 | D3 D3 | D6 ||')
>>> ah = abcFormat.ABCHandler()
>>> ah.process(abcStr)
>>> tokenColls = ah.splitByVoice()
>>> tokenColls[0]
<music21.abcFormat.ABCHandler object at 0x...>

Common headers are first

>>> [t.src for t in tokenColls[0].tokens]
['M:6/8', 'L:1/8', 'K:G']

Then each voice

>>> [t.src for t in tokenColls[1].tokens]
['V:1 name="Whistle" snm="wh"', 'B3', 'A3', '|', 'G6', '|', 'B3', 'A3', '|', 'G6', '||']
>>> [t.src for t in tokenColls[2].tokens]
['V:2 name="violin" snm="v"', 'B', 'd', 'B', 'A', 'c', 'A', '|',
 'G', 'A', 'G', 'D3', '|', 'B', 'd', 'B', 'A', 'c', 'A', '|', 'G', 'A', 'G', 'D6', '||']
>>> [t.src for t in tokenColls[3].tokens]
['V:3 name="Bass" snm="b" clef=bass', 'D3', 'D3', '|', 'D6', '|',
 'D3', 'D3', '|', 'D6', '||']

Then later the metadata can be merged at the start of each voice…

>>> mergedTokens = tokenColls[0] + tokenColls[1]
>>> mergedTokens
<music21.abcFormat.ABCHandler object at 0x...>
>>> [t.src for t in mergedTokens.tokens]
['M:6/8', 'L:1/8', 'K:G', 'V:1 name="Whistle" snm="wh"',
 'B3', 'A3', '|', 'G6', '|', 'B3', 'A3', '|', 'G6', '||']
static ABCHandler.startsMetadata(c: str, cNext: Optional[str], cNextNext: Optional[str]) → bool

Returns True if this context describes the start of a metadata section, like

A:something

Metadata: capital letter, with next char as ‘:’ and some following character

>>> ah = abcFormat.ABCHandler
>>> ah.startsMetadata('A', ':', 's')
True

lowercase w: is a special case for lyric defs

>>> ah.startsMetadata('w', ':', 's')
True

Following char must be “:”

>>> ah.startsMetadata('A', ' ', 's')
False

Pipe after colon indicates not metadata (bar info). For example need to not misinterpret repeat bars as metadata e.g. dAG FED:|2 dAG FGA|

this is incorrect, but we can avoid it by looking for a leading pipe and returning False

>>> ah.startsMetadata('A', ':', '|')
False
>>> ah.startsMetadata('A', ':', None)
False
ABCHandler.tokenProcess()

Process all token objects. First, calls preParse(), then does context assignments, then calls parse().

ABCHandler.tokenize(strSrc: str) → None

Walk the abc string, creating ABC objects along the way.

This may be called separately from process(), in the case that pre/post parse processing is not needed.

>>> abch = abcFormat.ABCHandler()
>>> abch.tokens
[]
>>> abch.tokenize('X: 1')
>>> abch.tokens
[<music21.abcFormat.ABCMetadata 'X: 1'>]
>>> abch = abcFormat.ABCHandler()
>>> abch.tokenize('(6f')
>>> abch.tokens
[<music21.abcFormat.ABCTuplet '(6'>, <music21.abcFormat.ABCNote 'f'>]
>>> abch = abcFormat.ABCHandler()
>>> abch.tokenize('(6:4f')
>>> abch.tokens
[<music21.abcFormat.ABCTuplet '(6:4'>, <music21.abcFormat.ABCNote 'f'>]
>>> abch = abcFormat.ABCHandler()
>>> abch.tokenize('(6:4:2f')
>>> abch.tokens
[<music21.abcFormat.ABCTuplet '(6:4:2'>, <music21.abcFormat.ABCNote 'f'>]
>>> abch = abcFormat.ABCHandler()
>>> abch.tokenize('(6::2f')
>>> abch.tokens
[<music21.abcFormat.ABCTuplet '(6::2'>, <music21.abcFormat.ABCNote 'f'>]
ABCHandler.tokensToBarIndices() → List[int]

Return a list of indices indicating which tokens in self.tokens are bar lines or the last piece of metadata before a note or chord.

ABCAccent

class music21.abcFormat.ABCAccent(src='')

ABCAccent tokens “K” precede a note or chord; they are a property of that note/chord. These appear as “>” in the output.

ABCAccent bases

ABCAccent read-only properties

Read-only properties inherited from ProtoM21Object:

ABCAccent methods

Methods inherited from ABCToken:

Methods inherited from ProtoM21Object:

ABCBar

class music21.abcFormat.ABCBar(src)

ABCBar bases

ABCBar read-only properties

Read-only properties inherited from ProtoM21Object:

ABCBar methods

ABCBar.getBarObject() → Optional[music21.bar.Barline]

Return a music21 bar object

>>> ab = abcFormat.ABCBar('|:')
>>> ab.parse()
>>> barObject = ab.getBarObject()
>>> barObject
 <music21.bar.Repeat direction=start>
ABCBar.isRegular() → bool

Return True if this is a regular, single, light bar line.

>>> ab = abcFormat.ABCBar('|')
>>> ab.parse()
>>> ab.isRegular()
True
ABCBar.isRepeat()
ABCBar.isRepeatBracket() → Union[int, bool]

Return a number if this defines a repeat bracket for an alternate ending otherwise returns False.

>>> ab = abcFormat.ABCBar('[2')
>>> ab.parse()
>>> ab.isRepeat()
False
>>> ab.isRepeatBracket()
2
ABCBar.parse()

Assign the bar-type based on the source string.

>>> ab = abcFormat.ABCBar('|')
>>> ab.parse()
>>> ab
<music21.abcFormat.ABCBar '|'>
>>> ab.barType
'barline'
>>> ab.barStyle
'regular'
>>> ab = abcFormat.ABCBar('||')
>>> ab.parse()
>>> ab.barType
'barline'
>>> ab.barStyle
'light-light'
>>> ab = abcFormat.ABCBar('|:')
>>> ab.parse()
>>> ab.barType
'repeat'
>>> ab.barStyle
'heavy-light'
>>> ab.repeatForm
'start'

Methods inherited from ABCToken:

Methods inherited from ProtoM21Object:

ABCBrokenRhythmMarker

class music21.abcFormat.ABCBrokenRhythmMarker(src)

Marks that rhythm is broken with ‘>>>’

ABCBrokenRhythmMarker bases

ABCBrokenRhythmMarker read-only properties

Read-only properties inherited from ProtoM21Object:

ABCBrokenRhythmMarker methods

ABCBrokenRhythmMarker.preParse()

Called before context adjustments: need to have access to data

>>> brokenRhythm = abcFormat.ABCBrokenRhythmMarker('>>>')
>>> brokenRhythm.preParse()
>>> brokenRhythm.data
'>>>'

Methods inherited from ABCToken:

Methods inherited from ProtoM21Object:

ABCChord

class music21.abcFormat.ABCChord(src: str = '')

A representation of an ABC Chord, which contains within its delimiters individual notes.

A subclass of ABCNote.

ABCChord bases

ABCChord read-only properties

Read-only properties inherited from ProtoM21Object:

ABCChord methods

ABCChord.parse(forceKeySignature=None, forceDefaultQuarterLength=None)

Handles the following types of chords:

  • Chord without length modifier: [ceg]

  • Chords with outer length modifier: [ceg]2, [ceg]/2

  • Chords with inner length modifier: [c2e2g2], [c2eg]

  • Chords with inner and outer length modifier: [c2e2g2]/2, [c/2e/2g/2]2

Methods inherited from ABCNote:

Methods inherited from ABCToken:

Methods inherited from ProtoM21Object:

ABCCrescStart

class music21.abcFormat.ABCCrescStart(src)

ABCCrescStart tokens always precede the notes in a crescendo. These tokens coincide with the string “!crescendo(“; the closing string “!crescendo)” counts as an ABCParenStop.

ABCCrescStart bases

ABCCrescStart read-only properties

Read-only properties inherited from ProtoM21Object:

ABCCrescStart methods

ABCCrescStart.fillCresc()

Methods inherited from ABCToken:

Methods inherited from ProtoM21Object:

ABCDimStart

class music21.abcFormat.ABCDimStart(src)

ABCDimStart tokens always precede the notes in a diminuendo. They function identically to ABCCrescStart tokens.

ABCDimStart bases

ABCDimStart read-only properties

Read-only properties inherited from ProtoM21Object:

ABCDimStart methods

ABCDimStart.fillDim()

Methods inherited from ABCToken:

Methods inherited from ProtoM21Object:

ABCDownbow

class music21.abcFormat.ABCDownbow(src='')

ABCStaccato tokens “.” precede a note or chord; they are a property of that note/chord.

ABCDownbow bases

ABCDownbow read-only properties

Read-only properties inherited from ProtoM21Object:

ABCDownbow methods

Methods inherited from ABCToken:

Methods inherited from ProtoM21Object:

ABCGraceStart

class music21.abcFormat.ABCGraceStart(src='')

Grace note start

ABCGraceStart bases

ABCGraceStart read-only properties

Read-only properties inherited from ProtoM21Object:

ABCGraceStart methods

Methods inherited from ABCToken:

Methods inherited from ProtoM21Object:

ABCGraceStop

class music21.abcFormat.ABCGraceStop(src='')

Grace note end

ABCGraceStop bases

ABCGraceStop read-only properties

Read-only properties inherited from ProtoM21Object:

ABCGraceStop methods

Methods inherited from ABCToken:

Methods inherited from ProtoM21Object:

ABCMetadata

class music21.abcFormat.ABCMetadata(src='')

Defines a token of metadata in ABC.

>>> md = abcFormat.ABCMetadata('I:linebreak')
>>> md.src
'I:linebreak'

Has two attributes, tag and data which are strings or None. Initially both are set to None:

>>> print(md.tag)
None

After calling preParse(), these are separated:

>>> md.preParse()
>>> md.tag
'I'
>>> md.data
'linebreak'

ABCMetadata bases

ABCMetadata read-only properties

Read-only properties inherited from ProtoM21Object:

ABCMetadata methods

ABCMetadata.getClefObject() → Tuple[Optional[music21.clef.Clef], Optional[int]]

Extract any clef parameters stored in the key metadata token. Assume that a clef definition suggests a transposition. Return both the Clef and the transposition.

Returns a two-element tuple of clefObj and transposition in semitones

>>> am = abcFormat.ABCMetadata('K:Eb Lydian bass')
>>> am.preParse()
>>> am.getClefObject()
(<music21.clef.BassClef>, -24)
ABCMetadata.getDefaultQuarterLength() → float

If there is a quarter length representation available, return it as a floating point value

>>> am = abcFormat.ABCMetadata('L:1/2')
>>> am.preParse()
>>> am.getDefaultQuarterLength()
2.0
>>> am = abcFormat.ABCMetadata('L:1/8')
>>> am.preParse()
>>> am.getDefaultQuarterLength()
0.5
>>> am = abcFormat.ABCMetadata('M:C|')
>>> am.preParse()
>>> am.getDefaultQuarterLength()
0.5

If taking from meter, find the “fraction” and if < 0.75 use sixteenth notes. If >= 0.75 use eighth notes.

>>> am = abcFormat.ABCMetadata('M:2/4')
>>> am.preParse()
>>> am.getDefaultQuarterLength()
0.25
>>> am = abcFormat.ABCMetadata('M:3/4')
>>> am.preParse()
>>> am.getDefaultQuarterLength()
0.5
>>> am = abcFormat.ABCMetadata('M:6/8')
>>> am.preParse()
>>> am.getDefaultQuarterLength()
0.5

Meter is only used for default length if there is no L:

>>> x = 'L:1/4\nM:3/4\n\nf'
>>> sc = converter.parse(x, format='abc')
>>> sc.recurse().notes.first().duration.type
'quarter'
ABCMetadata.getKeySignatureObject()

Return a music21 KeySignature or Key object for this metadata tag.

>>> am = abcFormat.ABCMetadata('K:G')
>>> am.preParse()
>>> ks = am.getKeySignatureObject()
>>> ks
<music21.key.Key of G major>
>>> am = abcFormat.ABCMetadata('K:Gmin')
>>> am.preParse()
>>> ks = am.getKeySignatureObject()
>>> ks
<music21.key.Key of g minor>
>>> ks.sharps
-2

Note that capitalization does not matter (http://abcnotation.com/wiki/abc:standard:v2.1#kkey) so this should still be minor.

>>> am = abcFormat.ABCMetadata('K:GM')
>>> am.preParse()
>>> ks = am.getKeySignatureObject()
>>> ks
<music21.key.Key of g minor>
ABCMetadata.getKeySignatureParameters()

Extract key signature parameters, include indications for mode, and translate sharps count compatible with m21, returning the number of sharps and the mode.

>>> from music21 import abcFormat
>>> am = abcFormat.ABCMetadata('K:Eb Lydian')
>>> am.preParse()
>>> am.getKeySignatureParameters()
(-2, 'lydian')
>>> am = abcFormat.ABCMetadata('K:APhry')
>>> am.preParse()
>>> am.getKeySignatureParameters()
(-1, 'phrygian')
>>> am = abcFormat.ABCMetadata('K:G Mixolydian')
>>> am.preParse()
>>> am.getKeySignatureParameters()
(0, 'mixolydian')
>>> am = abcFormat.ABCMetadata('K: Edor')
>>> am.preParse()
>>> am.getKeySignatureParameters()
(2, 'dorian')
>>> am = abcFormat.ABCMetadata('K: F')
>>> am.preParse()
>>> am.getKeySignatureParameters()
(-1, 'major')
>>> am = abcFormat.ABCMetadata('K:G')
>>> am.preParse()
>>> am.getKeySignatureParameters()
(1, 'major')
>>> am = abcFormat.ABCMetadata('K:Gm')
>>> am.preParse()
>>> am.getKeySignatureParameters()
(-2, 'minor')
>>> am = abcFormat.ABCMetadata('K:Hp')
>>> am.preParse()
>>> am.getKeySignatureParameters()
(2, None)
>>> am = abcFormat.ABCMetadata('K:G ionian')
>>> am.preParse()
>>> am.getKeySignatureParameters()
(1, 'ionian')
>>> am = abcFormat.ABCMetadata('K:G aeol')
>>> am.preParse()
>>> am.getKeySignatureParameters()
(-2, 'aeolian')
ABCMetadata.getMetronomeMarkObject() → Optional[music21.tempo.MetronomeMark]

Extract any tempo parameters stored in a tempo metadata token.

>>> am = abcFormat.ABCMetadata('Q: "Allegro" 1/4=120')
>>> am.preParse()
>>> am.getMetronomeMarkObject()
<music21.tempo.MetronomeMark Allegro Quarter=120.0>
>>> am = abcFormat.ABCMetadata('Q: 3/8=50 "Slowly"')
>>> am.preParse()
>>> am.getMetronomeMarkObject()
<music21.tempo.MetronomeMark Slowly Dotted Quarter=50.0>
>>> am = abcFormat.ABCMetadata('Q:1/2=120')
>>> am.preParse()
>>> am.getMetronomeMarkObject()
<music21.tempo.MetronomeMark animato Half=120.0>
>>> am = abcFormat.ABCMetadata('Q:1/4 3/8 1/4 3/8=40')
>>> am.preParse()
>>> am.getMetronomeMarkObject()
<music21.tempo.MetronomeMark grave Whole tied to Quarter (5 total QL)=40.0>
>>> am = abcFormat.ABCMetadata('Q:90')
>>> am.preParse()
>>> am.getMetronomeMarkObject()
<music21.tempo.MetronomeMark maestoso Quarter=90.0>
ABCMetadata.getTimeSignatureObject()

Return a music21 TimeSignature object for this metadata tag, if isMeter is True, otherwise raise exception.

>>> am = abcFormat.ABCMetadata('M:2/2')
>>> am.preParse()
>>> ts = am.getTimeSignatureObject()
>>> ts
<music21.meter.TimeSignature 2/2>
>>> am = abcFormat.ABCMetadata('Q:40')
>>> am.getTimeSignatureObject()
Traceback (most recent call last):
music21.abcFormat.ABCTokenException: no time signature associated with
    this non-metrical metadata.
ABCMetadata.getTimeSignatureParameters()

If there is a time signature representation available, get a numerator, denominator and an abbreviation symbol. To get a music21 TimeSignature object, use the getTimeSignatureObject() method.

>>> am = abcFormat.ABCMetadata('M:2/2')
>>> am.preParse()
>>> am.isMeter()
True
>>> am.getTimeSignatureParameters()
(2, 2, 'normal')
>>> am = abcFormat.ABCMetadata('M:C|')
>>> am.preParse()
>>> am.getTimeSignatureParameters()
(2, 2, 'cut')
>>> am = abcFormat.ABCMetadata('M: none')
>>> am.preParse()
>>> am.getTimeSignatureParameters() is None
True
>>> am = abcFormat.ABCMetadata('M: FREI4/4')
>>> am.preParse()
>>> am.getTimeSignatureParameters()
(4, 4, 'normal')
ABCMetadata.isComposer() → bool

Returns True if the tag is “C” for composer, False otherwise.

ABCMetadata.isDefaultNoteLength() → bool

Returns True if the tag is “L”, False otherwise.

ABCMetadata.isKey() → bool

Returns True if the tag is “K”, False otherwise. Note that in some cases a Key will encode clef information.

(example from corpus: josquin/laDeplorationDeLaMorteDeJohannesOckeghem.abc)

ABCMetadata.isMeter() → bool

Returns True if the tag is “M” for meter, False otherwise.

ABCMetadata.isOrigin() → bool

Returns True if the tag is “O” for origin, False otherwise. This value is set in the Metadata localOfComposition of field.

ABCMetadata.isReferenceNumber() → bool

Returns True if the tag is “X”, False otherwise.

>>> x = abcFormat.ABCMetadata('X:5')
>>> x.preParse()
>>> x.tag
'X'
>>> x.isReferenceNumber()
True
ABCMetadata.isTempo() → bool

Returns True if the tag is “Q” for tempo, False otherwise.

ABCMetadata.isTitle() → bool

Returns True if the tag is “T” for title, False otherwise.

ABCMetadata.isVoice() → bool

Returns True if the tag is “V”, False otherwise.

ABCMetadata.parse()

Dummy method that reads self.src and loads attributes. It is called after contextual adjustments.

It is designed to be subclassed or overridden.

ABCMetadata.preParse() → None

Called before contextual adjustments and needs to have access to data. Divides a token into .tag (a single capital letter or w) and .data representations.

>>> x = abcFormat.ABCMetadata('T:tagData')
>>> x.preParse()
>>> x.tag
'T'
>>> x.data
'tagData'

Methods inherited from ABCToken:

Methods inherited from ProtoM21Object:

ABCNote

class music21.abcFormat.ABCNote(src='', carriedAccidental=None)

A model of an ABCNote.

General usage requires multi-pass processing. After being tokenized, each ABCNote needs a number of attributes updates. Attributes to be updated after tokenizing, and based on the linear sequence of tokens: inBar, inBeam (not used), inGrace, activeDefaultQuarterLength, brokenRhythmMarker, and activeKeySignature.

The chordSymbols list stores one or more chord symbols (ABC calls these guitar chords) associated with this note. This attribute is updated when parse() is called.

ABCNote bases

ABCNote read-only properties

Read-only properties inherited from ProtoM21Object:

ABCNote methods

ABCNote.getPitchName(strSrc: str, forceKeySignature=None) → Tuple[Optional[str], Optional[bool]]

Given a note or rest string without a chord symbol, return a music21 pitch string or None (if a rest), and the accidental display status. This value is paired with an accidental display status. Pitch alterations, and accidental display status, are adjusted if a key is declared in the Note.

>>> an = abcFormat.ABCNote()
>>> an.getPitchName('e2')
('E5', None)
>>> an.getPitchName('C')
('C4', None)
>>> an.getPitchName('B,,')
('B2', None)
>>> an.getPitchName('C,')
('C3', None)
>>> an.getPitchName('c')
('C5', None)
>>> an.getPitchName("c'")
('C6', None)
>>> an.getPitchName("c''")
('C7', None)
>>> an.getPitchName("^g")
('G#5', True)
>>> an.getPitchName("_g''")
('G-7', True)
>>> an.getPitchName('=c')
('Cn5', True)

If pitch is a rest (z) then the Pitch name is None:

>>> an.getPitchName('z4')
(None, None)

Grace note:

>>> an.getPitchName('{c}')
('C5', None)

Given an active KeySignature object, the pitch name might change:

>>> an.activeKeySignature = key.KeySignature(3)
>>> an.getPitchName('c')
('C#5', False)

Illegal pitch names raise an ABCHandlerException

>>> an.getPitchName('x')
Traceback (most recent call last):
music21.abcFormat.ABCHandlerException: cannot find any pitch information in: 'x'
ABCNote.getQuarterLength(strSrc, forceDefaultQuarterLength=None) → float

Called with parse(), after context processing, to calculate duration

>>> an = abcFormat.ABCNote()
>>> an.activeDefaultQuarterLength = 0.5
>>> an.getQuarterLength('e2')
1.0
>>> an.getQuarterLength('G')
0.5
>>> an.getQuarterLength('=c/2')
0.25
>>> an.getQuarterLength('A3/2')
0.75
>>> an.getQuarterLength('A/')
0.25
>>> an.getQuarterLength('A//')
0.125
>>> an.getQuarterLength('A///')
0.0625
>>> an = abcFormat.ABCNote()
>>> an.activeDefaultQuarterLength = 0.5
>>> an.brokenRhythmMarker = ('>', 'left')
>>> an.getQuarterLength('A')
0.75
>>> an.brokenRhythmMarker = ('>', 'right')
>>> an.getQuarterLength('A')
0.25
>>> an.brokenRhythmMarker = ('<<', 'left')
>>> an.getQuarterLength('A')
0.125
>>> an.brokenRhythmMarker = ('<<', 'right')
>>> an.getQuarterLength('A')
0.875
>>> an.brokenRhythmMarker = ('<<<', 'left')
>>> an.getQuarterLength('A')
0.0625
>>> an.brokenRhythmMarker = ('<<<', 'right')
>>> an.getQuarterLength('A')
0.9375
>>> an.getQuarterLength('A', forceDefaultQuarterLength=1)
1.875
ABCNote.parse(forceDefaultQuarterLength=None, forceKeySignature=None) → None

Dummy method that reads self.src and loads attributes. It is called after contextual adjustments.

It is designed to be subclassed or overridden.

Methods inherited from ABCToken:

Methods inherited from ProtoM21Object:

ABCParenStop

class music21.abcFormat.ABCParenStop(src='')

A general parenthesis stop; comes at the end of a tuplet, slur, or dynamic marking.

ABCParenStop bases

ABCParenStop read-only properties

Read-only properties inherited from ProtoM21Object:

ABCParenStop methods

Methods inherited from ABCToken:

Methods inherited from ProtoM21Object:

ABCSlurStart

class music21.abcFormat.ABCSlurStart(src)

ABCSlurStart tokens always precede the notes in a slur. For nested slurs, each open parenthesis gets its own token.

ABCSlurStart bases

ABCSlurStart read-only properties

Read-only properties inherited from ProtoM21Object:

ABCSlurStart methods

ABCSlurStart.fillSlur()

Creates a spanner object for each open paren associated with a slur; these slurs are filled with notes until end parens are read.

Methods inherited from ABCToken:

Methods inherited from ProtoM21Object:

ABCStaccato

class music21.abcFormat.ABCStaccato(src='')

ABCStaccato tokens “.” precede a note or chord; they are a property of that note/chord.

ABCStaccato bases

ABCStaccato read-only properties

Read-only properties inherited from ProtoM21Object:

ABCStaccato methods

Methods inherited from ABCToken:

Methods inherited from ProtoM21Object:

ABCStraccent

class music21.abcFormat.ABCStraccent(src='')

ABCStraccent tokens “k” precede a note or chord; they are a property of that note/chord. These appear as “^” in the output.

ABCStraccent bases

ABCStraccent read-only properties

Read-only properties inherited from ProtoM21Object:

ABCStraccent methods

Methods inherited from ABCToken:

Methods inherited from ProtoM21Object:

ABCTenuto

class music21.abcFormat.ABCTenuto(src='')

ABCTenuto tokens “M” precede a note or chord; they are a property of that note/chord.

ABCTenuto bases

ABCTenuto read-only properties

Read-only properties inherited from ProtoM21Object:

ABCTenuto methods

Methods inherited from ABCToken:

Methods inherited from ProtoM21Object:

ABCTie

class music21.abcFormat.ABCTie(src)

Handles instances of ties ‘-‘ between notes in an ABC score. Ties are treated as an attribute of the note before the ‘-‘; the note after is marked as the end of the tie.

ABCTie bases

ABCTie read-only properties

Read-only properties inherited from ProtoM21Object:

ABCTie methods

Methods inherited from ABCToken:

Methods inherited from ProtoM21Object:

ABCToken

class music21.abcFormat.ABCToken(src='')

ABC processing works with a multi-pass procedure. The first pass breaks the data stream into a list of ABCToken objects. ABCToken objects are specialized in subclasses.

The multi-pass procedure is conducted by an ABCHandler object. The ABCHandler.tokenize() method breaks the data stream into ABCToken objects. The tokenProcess() method first calls the preParse() method on each token, then does contextual adjustments to all tokens, then calls parse() on all tokens.

The source ABC string itself is stored in self.src

ABCToken bases

ABCToken read-only properties

Read-only properties inherited from ProtoM21Object:

ABCToken methods

ABCToken.parse()

Dummy method that reads self.src and loads attributes. It is called after contextual adjustments.

It is designed to be subclassed or overridden.

ABCToken.preParse()

Dummy method that is called before contextual adjustments. Designed to be subclassed or overridden.

static ABCToken.stripComment(strSrc)

removes ABC-style comments from a string:

>>> ao = abcFormat.ABCToken()
>>> ao.stripComment('asdf')
'asdf'
>>> ao.stripComment('asdf%234')
'asdf'
>>> ao.stripComment('asdf  %     234')
'asdf  '
>>> ao.stripComment('[ceg]% this chord appears 50% more often than other chords do')
'[ceg]'

This is a static method, so it can also be called on the class itself:

>>> abcFormat.ABCToken.stripComment('b1 % a b-flat actually')
'b1 '

Changed: v6.2 – made a staticmethod

Methods inherited from ProtoM21Object:

ABCTuplet

class music21.abcFormat.ABCTuplet(src)

ABCTuplet tokens always precede the notes they describe.

In ABCHandler.tokenProcess(), rhythms are adjusted.

ABCTuplet bases

ABCTuplet read-only properties

Read-only properties inherited from ProtoM21Object:

ABCTuplet methods

ABCTuplet.updateNoteCount()

Update the note count of notes that are affected by this tuplet. Can be set by p:q:r style tuplets. Also creates a tuplet object.

>>> at = abcFormat.ABCTuplet('(6')
>>> at.updateRatio()
>>> at.updateNoteCount()
>>> at.noteCount
6
>>> at.tupletObj
<music21.duration.Tuplet 6/2>
>>> at = abcFormat.ABCTuplet('(6:4:12')
>>> at.updateRatio()
>>> at.updateNoteCount()
>>> at.noteCount
12
>>> at.tupletObj
<music21.duration.Tuplet 6/4>
>>> at = abcFormat.ABCTuplet('(6::18')
>>> at.updateRatio()
>>> at.updateNoteCount()
>>> at.noteCount
18
ABCTuplet.updateRatio(keySignatureObj=None)

Cannot be called until local meter context is established.

>>> at = abcFormat.ABCTuplet('(3')
>>> at.updateRatio()
>>> at.numberNotesActual, at.numberNotesNormal
(3, 2)

Generally a 5:n tuplet is 5 in the place of 2.

>>> at = abcFormat.ABCTuplet('(5')
>>> at.updateRatio()
>>> at.numberNotesActual, at.numberNotesNormal
(5, 2)

Unless it’s in a meter.TimeSignature compound (triple) context:

>>> at = abcFormat.ABCTuplet('(5')
>>> at.updateRatio(meter.TimeSignature('6/8'))
>>> at.numberNotesActual, at.numberNotesNormal
(5, 3)

Six is 6:2, not 6:4!

>>> at = abcFormat.ABCTuplet('(6')
>>> at.updateRatio()
>>> at.numberNotesActual, at.numberNotesNormal
(6, 2)
>>> at = abcFormat.ABCTuplet('(6:4')
>>> at.updateRatio()
>>> at.numberNotesActual, at.numberNotesNormal
(6, 4)
>>> at = abcFormat.ABCTuplet('(6::6')
>>> at.updateRatio()
>>> at.numberNotesActual, at.numberNotesNormal
(6, 2)

2 is 2 in 3…

>>> at = abcFormat.ABCTuplet('(2')
>>> at.updateRatio()
>>> at.numberNotesActual, at.numberNotesNormal
(2, 3)

Some other types:

>>> for n in 1, 2, 3, 4, 5, 6, 7, 8, 9:
...     at = abcFormat.ABCTuplet(f'({n}')
...     at.updateRatio()
...     print(at.numberNotesActual, at.numberNotesNormal)
1 1
2 3
3 2
4 3
5 2
6 2
7 2
8 3
9 2

Tuplets > 9 raise an exception:

>>> at = abcFormat.ABCTuplet('(10')
>>> at.updateRatio()
Traceback (most recent call last):
music21.abcFormat.ABCTokenException: cannot handle tuplet of form: '(10'

Methods inherited from ABCToken:

Methods inherited from ProtoM21Object:

ABCUpbow

class music21.abcFormat.ABCUpbow(src='')

ABCStaccato tokens “.” precede a note or chord; they are a property of that note/chord.

ABCUpbow bases

ABCUpbow read-only properties

Read-only properties inherited from ProtoM21Object:

ABCUpbow methods

Methods inherited from ABCToken:

Methods inherited from ProtoM21Object:

Functions

music21.abcFormat.mergeLeadingMetaData(barHandlers: List[music21.abcFormat.ABCHandlerBar]) → List[music21.abcFormat.ABCHandlerBar]

Given a list of ABCHandlerBar objects, return a list of ABCHandlerBar objects where leading metadata is merged, if possible, with the bar data following.

This consolidates all metadata in bar-like entities.