Created
September 11, 2019 15:23
-
-
Save adammichaelwood/2c575c1bbae356c3d6d300486bec5f6e to your computer and use it in GitHub Desktop.
music21 helpers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import music21 as m | |
import copy | |
# replace x.show('midi') with play(x) | |
# to solve problem of first note(s) not playing | |
# in many web browsers | |
def play(x): | |
"""Returns nothing. Outputs a midi realization of x, a note or stream. | |
Primarily for use in notebooks and web environments. | |
""" | |
if isinstance(x, m.stream.Stream): | |
x = copy.deepcopy(x) | |
for subStream in x.recurse(streamsOnly=True, includeSelf=True): | |
mss = subStream.getElementsByClass(m.stream.Measure) | |
for ms in mss: | |
ms.offset += 1.0 | |
if isinstance(x, m.note.Note): | |
s = m.stream.Stream() | |
s.append(m.note.Rest(1)) | |
s.append(x) | |
x = s | |
x.show('midi') | |
###### | |
def tiny(x): | |
""" Returns a stream based on x, a string of tinynotation | |
which may include chords: | |
"c e g chord{c e g}" | |
Do not include 'tinynotation: ' in the string. | |
""" | |
tnc = m.tinyNotation.Converter(x) | |
tnc.bracketStateMapping['chord'] = ChordState | |
s = tnc.parse().stream | |
return s | |
# this class is from the music21 documentation | |
class ChordState(m.tinyNotation.State): | |
def affectTokenAfterParse(self, n): | |
super().affectTokenAfterParse(n) | |
return None # do not append Note object | |
def end(self): | |
ch = m.chord.Chord(self.affectedTokens) | |
ch.duration = self.affectedTokens[0].duration | |
return ch | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment