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: 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.
Functions¶
-
music21.abcFormat.
mergeLeadingMetaData
(barHandlers)¶ 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.
ABCFile¶
-
class
music21.abcFormat.
ABCFile
¶ ABC File or String access
ABCFile
methods
-
ABCFile.
close
()¶
-
ABCFile.
extractReferenceNumber
(strSrc, number)¶ 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.
-
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 readstring, which processes all tokens.
If number is given, a work number will be extracted if possible.
-
ABCFile.
readstr
(strSrc, number=None)¶ Read a string and process all Tokens. Returns a ABCHandler instance.
ABCHandler¶
-
class
music21.abcFormat.
ABCHandler
¶
ABCHandler
read/write properties
-
ABCHandler.
tokens
¶ Get or set tokens for this Handler
ABCHandler
methods
-
ABCHandler.
barlineTokenFilter
(token)¶ 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 '|:'>]
-
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
()¶ Get the first title tag. Used for testing.
Requires tokens to have been processed.
-
ABCHandler.
hasNotes
()¶ 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.
process
(strSrc)¶
-
ABCHandler.
splitByMeasure
()¶ 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 >>> len(ahDict[5].tokens) 14
-
ABCHandler.
splitByVoice
()¶ 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', '||']
-
ABCHandler.
tokenProcess
()¶ Process all token objects. First, calls preParse(), then does context assignments, then calls parse().
-
ABCHandler.
tokenize
(strSrc)¶ 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'>]
ABCHandlerBar¶
-
class
music21.abcFormat.
ABCHandlerBar
¶ 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¶
-
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
methods
Methods inherited from ABCToken
:
ABCBar¶
-
class
music21.abcFormat.
ABCBar
(src)¶
ABCBar
bases
ABCBar
methods
-
ABCBar.
getBarObject
()¶ Return a music21 bar object
>>> ab = abcFormat.ABCBar('|:') >>> ab.parse() >>> post = ab.getBarObject()
-
ABCBar.
isRegular
()¶ Return True if this is a regular, single, light bar line.
>>> ab = abcFormat.ABCBar('|') >>> ab.parse() >>> ab.isRegular() True
-
ABCBar.
isRepeat
()¶
-
ABCBar.
isRepeatBracket
()¶ Return true if this defines a repeat bracket for an alternate ending
>>> 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
:
ABCBrokenRhythmMarker¶
-
class
music21.abcFormat.
ABCBrokenRhythmMarker
(src)¶
ABCBrokenRhythmMarker
bases
ABCBrokenRhythmMarker
methods
-
ABCBrokenRhythmMarker.
preParse
()¶ Called before context adjustments: need to have access to data
>>> abrm = abcFormat.ABCBrokenRhythmMarker('>>>') >>> abrm.preParse() >>> abrm.data '>>>'
Methods inherited from ABCToken
:
ABCChord¶
-
class
music21.abcFormat.
ABCChord
(src)¶ A representation of an ABC Chord, which contains within its delimiters individual notes.
A subclass of ABCNote.
ABCChord
bases
ABCChord
methods
-
ABCChord.
parse
(forceKeySignature=None, forceDefaultQuarterLength=None)¶
Methods inherited from ABCToken
:
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
methods
-
ABCCrescStart.
fillCresc
()¶
Methods inherited from ABCToken
:
ABCDimStart¶
-
class
music21.abcFormat.
ABCDimStart
(src)¶ ABCDimStart tokens always precede the notes in a diminuendo. They function identically to ABCCrescStart tokens.
ABCDimStart
bases
ABCDimStart
methods
-
ABCDimStart.
fillDim
()¶
Methods inherited from ABCToken
:
ABCDownbow¶
-
class
music21.abcFormat.
ABCDownbow
(src='')¶ ABCStaccato tokens ”.” precede a note or chord; they are a property of that note/chord.
ABCDownbow
bases
ABCDownbow
methods
Methods inherited from ABCToken
:
ABCGraceStart¶
-
class
music21.abcFormat.
ABCGraceStart
(src='')¶
ABCGraceStart
bases
ABCGraceStart
methods
Methods inherited from ABCToken
:
ABCGraceStop¶
-
class
music21.abcFormat.
ABCGraceStop
(src='')¶
ABCGraceStop
bases
ABCGraceStop
methods
Methods inherited from ABCToken
:
ABCMetadata¶
-
class
music21.abcFormat.
ABCMetadata
(src='')¶
ABCMetadata
bases
ABCMetadata
methods
-
ABCMetadata.
getClefObject
()¶ 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
()¶ 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
-
ABCMetadata.
getKeySignatureObject
()¶ 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>
-
ABCMetadata.
getMetronomeMarkObject
()¶ 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.>>> am = abcFormat.ABCMetadata('M:2/2') >>> am.preParse() >>> ts = am.getTimeSignatureObject() >>> ts <music21.meter.TimeSignature 2/2>
-
ABCMetadata.
isComposer
()¶ Returns True if the tag is “C” for composer, False otherwise.
-
ABCMetadata.
isDefaultNoteLength
()¶ Returns True if the tag is “L”, False otherwise.
-
ABCMetadata.
isKey
()¶ Returns True if the tag is “K”, False otherwise. Note that in some cases a Key will encode clef information.
-
ABCMetadata.
isMeter
()¶ Returns True if the tag is “M” for meter, False otherwise.
-
ABCMetadata.
isOrigin
()¶ Returns True if the tag is “O” for origin, False otherwise. This value is set in the Metadata localOfComposition of field.
-
ABCMetadata.
isReferenceNumber
()¶ Returns True if the tag is “X”, False otherwise.
>>> x = abcFormat.ABCMetadata('X:5') >>> x.preParse() >>> x.tag 'X' >>> x.isReferenceNumber() True
-
ABCMetadata.
isTempo
()¶ Returns True if the tag is “Q” for tempo, False otherwise.
-
ABCMetadata.
isTitle
()¶ Returns True if the tag is “T” for title, False otherwise.
-
ABCMetadata.
isVoice
()¶ Returns True if the tag is “V”, False otherwise.
-
ABCMetadata.
parse
()¶
-
ABCMetadata.
preParse
()¶ 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
:
ABCNote¶
-
class
music21.abcFormat.
ABCNote
(src='')¶ 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
-
ABCNote.
parse
(forceDefaultQuarterLength=None, forceKeySignature=None)¶
Methods inherited from ABCToken
:
ABCParenStop¶
-
class
music21.abcFormat.
ABCParenStop
(src)¶ A general parenthesis stop; comes at the end of a tuplet, slur, or dynamic marking.
ABCParenStop
bases
ABCParenStop
methods
Methods inherited from ABCToken
:
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
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
:
ABCStaccato¶
-
class
music21.abcFormat.
ABCStaccato
(src='')¶ ABCStaccato tokens ”.” precede a note or chord; they are a property of that note/chord.
ABCStaccato
bases
ABCStaccato
methods
Methods inherited from ABCToken
:
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
methods
Methods inherited from ABCToken
:
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
methods
Methods inherited from ABCToken
:
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
methods
Methods inherited from ABCToken
:
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 thepreParse()
method on each token, then does contextual adjustments to all tokens, then callsparse()
on all tokens.The source ABC string itself is stored in self.src
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.
-
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]'
ABCTuplet¶
-
class
music21.abcFormat.
ABCTuplet
(src)¶ ABCTuplet tokens always precede the notes they describe.
In ABCHandler.tokenProcess(), rhythms are adjusted.
ABCTuplet
bases
ABCTuplet
methods
-
ABCTuplet.
updateNoteCount
(durationActual=None, durationNormal=None)¶ Update the note count of notes that are affected by this tuplet.
-
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)
>>> 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
: