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: http://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.
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.
ABC File or String access
ABCFile methods
Extract a single reference number from many defined in a file. This permits loading a single work from a collection/opus without parsing the entire file.
Open a file for reading
Assign a file-like object, such as those provided by StringIO, as an open file object.
>>> from io import StringIO
>>> fileLikeOpen = StringIO()
Read a file. Note that this calls readstring, which processes all tokens.
If number is given, a work number will be extracted if possible.
Read a string and process all Tokens. Returns a ABCHandler instance.
ABCHandler read/write properties
Get or set tokens for this Handler
ABCHandler methods
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.
>>> abch = abcFormat.ABCHandler()
>>> abch.barlineTokenFilter('::')
[<music21.abcFormat.ABCBar ':|'>, <music21.abcFormat.ABCBar '|:'>]
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
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
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'
Get the first title tag. Used for testing.
Requires tokens to have been processed.
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
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
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
>>> len(ahDict[5].tokens)
14
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()
>>> junk = ah.process(abcStr)
>>> tokenColls = ah.splitByVoice()
>>> tokenColls[0]
<music21.abcFormat.ABCHandler object at 0x...>
>>> [t.src for t in tokenColls[0].tokens] # common headers are first
['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', '||']
Process all token objects. First, calls preParse(), then does context assignments, then calls parse().
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'>]
A Handler specialized for storing bars. All left and right bars are collected and assigned to attributes.
ABCHandlerBar bases
ABCHandlerBar read/write properties
Read/write properties inherited from ABCHandler:
ABCHandlerBar methods
Methods inherited from ABCHandler:
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 methods
Methods inherited from ABCToken:
ABCBar bases
ABCBar methods
Return a music21 bar object
>>> ab = abcFormat.ABCBar('|:')
>>> ab.parse()
>>> post = ab.getBarObject()
Return True if this is a regular, single, light bar line.
>>> ab = abcFormat.ABCBar('|')
>>> ab.parse()
>>> ab.isRegular()
True
Return true if this defines a repeat bracket for an alternate ending
>>> ab = abcFormat.ABCBar('[2')
>>> ab.parse()
>>> ab.isRepeat()
False
>>> ab.isRepeatBracket()
2
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:
ABCBrokenRhythmMarker bases
ABCBrokenRhythmMarker methods
Called before context adjustments: need to have access to data
>>> abrm = abcFormat.ABCBrokenRhythmMarker('>>>')
>>> abrm.preParse()
>>> abrm.data
'>>>'
Methods inherited from ABCToken:
A representation of an ABC Chord, which contains within its delimiters individual notes.
A subclass of ABCNote.
ABCChord bases
ABCChord methods
Methods inherited from ABCToken:
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 methods
Methods inherited from ABCToken:
ABCDimStart tokens always precede the notes in a diminuendo. They function identically to ABCCrescStart tokens.
ABCDimStart bases
ABCDimStart methods
Methods inherited from ABCToken:
ABCStaccato tokens ”.” precede a note or chord; they are a property of that note/chord.
ABCDownbow bases
ABCDownbow methods
Methods inherited from ABCToken:
ABCGraceStart bases
ABCGraceStart methods
Methods inherited from ABCToken:
ABCGraceStop bases
ABCGraceStop methods
Methods inherited from ABCToken:
ABCMetadata bases
ABCMetadata methods
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)
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
>>> am = abcFormat.ABCMetadata('M:2/4')
>>> am.preParse()
>>> am.getDefaultQuarterLength()
0.25
>>> am = abcFormat.ABCMetadata('M:6/8')
>>> am.preParse()
>>> am.getDefaultQuarterLength()
0.5
Return a music21 KeySignature object for this metadata tag.
>>> am = abcFormat.ABCMetadata('K:G')
>>> am.preParse()
>>> ks = am.getKeySignatureObject()
>>> ks
<music21.key.KeySignature of 1 sharp>
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>
Return a music21 TimeSignature object for this metadata tag.
>>> am = abcFormat.ABCMetadata('M:2/2')
>>> am.preParse()
>>> ts = am.getTimeSignatureObject()
>>> ts
<music21.meter.TimeSignature 2/2>
Returns True if the tag is “C” for composer, False otherwise.
Returns True if the tag is “L”, False otherwise.
Returns True if the tag is “K”, False otherwise. Note that in some cases a Key will encode clef information.
Returns True if the tag is “M” for meter, False otherwise.
Returns True if the tag is “O” for origin, False otherwise. This value is set in the Metadata localOfComposition of field.
Returns True if the tag is “X”, False otherwise.
>>> x = abcFormat.ABCMetadata('X:5')
>>> x.preParse()
>>> x.tag
'X'
>>> x.isReferenceNumber()
True
Returns True if the tag is “Q” for tempo, False otherwise.
Returns True if the tag is “T” for title, False otherwise.
Returns True if the tag is “V”, False otherwise.
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:
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 methods
Methods inherited from ABCToken:
A general parenthesis stop; comes at the end of a tuplet, slur, or dynamic marking.
ABCParenStop bases
ABCParenStop methods
Methods inherited from ABCToken:
ABCSlurStart tokens always precede the notes in a slur. For nested slurs, each open parenthesis gets its own token.
ABCSlurStart bases
ABCSlurStart methods
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:
ABCStaccato tokens ”.” precede a note or chord; they are a property of that note/chord.
ABCStaccato bases
ABCStaccato methods
Methods inherited from ABCToken:
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 methods
Methods inherited from ABCToken:
ABCTenuto tokens “M” precede a note or chord; they are a property of that note/chord.
ABCTenuto bases
ABCTenuto methods
Methods inherited from ABCToken:
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 methods
Methods inherited from ABCToken:
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 methods
Dummy method that reads self.src and loads attributes. It is called after contextual adjustments.
It is designed to be subclassed or overridden.
Dummy method that is called before contextual adjustments. Designed to be subclassed or overridden.
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]'
ABCTuplet tokens always precede the notes they describe.
In ABCHandler.tokenProcess(), rhythms are adjusted.
ABCTuplet bases
ABCTuplet methods
Update the note count of notes that are affected by this tuplet.
Cannot be called until local meter context is established.
>>> at = abcFormat.ABCTuplet('(3')
>>> at.updateRatio()
>>> at.numberNotesActual, at.numberNotesNormal
(3, 2)
>>> at = abcFormat.ABCTuplet('(5')
>>> at.updateRatio()
>>> at.numberNotesActual, at.numberNotesNormal
(5, 2)
>>> at = abcFormat.ABCTuplet('(5')
>>> at.updateRatio(meter.TimeSignature('6/8'))
>>> at.numberNotesActual, at.numberNotesNormal
(5, 3)
Methods inherited from ABCToken: