MObj

class maelzel.core.mobj.MObj(dur, offset=None, label='', parent=None, properties=None, symbols=None)[source]

Bases: ABC

This is the base class for all core objects.

This is an abstract class. It should not be instantiated by itself. A MObj can display itself via show() and play itself via play(). Any MObj has a duration (dur) and a time offset (offset). The offset can be left as None, indicating that it is not explicitely set, in which case it will be calculated from the context. In the case of events or chains, which can be contained within other objects, the offset depends on the previous objects. The resolved (implicit) offset can be queried via MObj.relOffset(). This offset is relative to the parent, or an absolute offset if the object has no parent. The absolute offset can be queried via MObj.absOffset().

A MObj can customize its playback via setPlay(). The playback attributes can be accessed through the playargs attribute

Elements purely related to notation (text annotations, articulations, etc) are added to a MObj through the addSymbol() and can be accessed through the MObj.symbols attribute. A symbol is an attribute or notation element (like color, size or an attached text expression) which has meaning only in the realm of graphical representation.

Parameters:
  • dur (F) – the duration of this object, in quarternotes

  • offset (F | None) – the (optional) time offset of this object, in quarternotes

  • label – a string label to identify this object, if necessary

Attributes Summary

dur

The duration of this object, in quarternotes

end

The end time of this object.

label

a label can be used to identify an object within a group of objects

offset

Optional offset, in quarternotes.

parent

The parent of this object.

playargs

playargs are set via setPlay() and are used to customize playback (instr, gain, …).

properties

User-defined properties as a dict (None by default).

symbols

A list of all symbols added via addSymbol() (None by default)

Methods Summary

absEnd()

Returns the absolute end of this offset, as quarternotes

absOffset()

Returns the absolute offset of this object in quarternotes

activeScorestruct()

Returns the ScoreStruct active for this obj or its parent.

addSymbol(*args, **kws)

Add a notation symbol to this object

addText(text[, placement, italic, weight, ...])

Add a text annotation to this object

clone(**kws)

Clone this object, changing parameters if needed

copy()

Returns a copy of this object

dump([indents, forcetext])

Prints all relevant information about this object

durSecs()

Returns the duration in seconds according to the active score

getConfig([prototype])

Returns a CoreConfig overloaded with options set for this object

getPlay(key[, default, recursive])

Get a playback attribute previously set via MObj.setPlay()

getProperty(key[, default])

Get a property of this objects

getSymbol(classname)

Get a symbol of a given class, if present

invertPitch(pivot)

Invert the pitch of this object

isRest()

Is this object a Rest?

location()

Returns the location of this object within the active score struct

meanPitch()

The mean pitch of this object

parentAbsOffset()

The absolute offset of the parent

pitchRange()

The pitch range of this object, if applicable

pitchTransform(pitchmap)

Apply a pitch-transform to this object, returns a copy

play([instr, delay, args, gain, chan, ...])

Plays this object.

plot([axes, figsize, timeSignatures, grid])

Plot this object

quantizePitch([step])

Returns a new object, with pitch rounded to step

quantizedScore([scorestruct, config, ...])

Returns a QuantizedScore representing this object

rec([outfile, sr, verbose, wait, nchnls, ...])

Record the output of .play as a soundfile

relEnd()

Resolved end of this object, relative to its parent

relOffset()

Resolve the offset of this object, relative to its parent

remap(deststruct[, sourcestruct])

Creates a clone, remapping times from source scorestruct to destination scorestruct

render([backend, renderoptions, ...])

Renders this object as notation

scorestruct()

Returns the ScoreStruct active for this obj or its parent (recursively)

scoringEvents([groupid, config, parentOffset])

Returns its notated form as scoring.Notations

scoringParts([config])

Returns this object as a list of scoring UnquantizedParts.

setPlay(**kws)

Set any playback attributes, returns self

setProperty(key, value)

Set a property, returns self

show([fmt, external, backend, scorestruct, ...])

Show this as notation.

synthEvents([instr, delay, args, gain, ...])

Returns the SynthEvents needed to play this object

timeRange()

Returns a tuple (starttime, endtime), in seconds

timeScale(factor[, offset])

Create a copy with modified timing by applying a linear transformation

timeShift(offset)

Return a copy of this object with an added offset

timeShiftInPlace(offset)

Shift the time of this by the given offset (inplace)

timeTransform(timemap[, inplace])

Apply a time-transform to this object

transpose(interval)

Transpose this object by the given interval

transposeByRatio(ratio)

Transpose this by a given frequency ratio, if applicable

unquantizedScore([title])

Create a maelzel.scoring.UnquantizedScore from this object

withExplicitOffset([forcecopy])

Copy of self with explicit times

write(outfile[, backend, resolution, format])

Export to multiple formats

Attributes Documentation

dur

The duration of this object, in quarternotes

end

The end time of this object.

Will be None if this object has no explicit offset. Use :meth:`

label: str

a label can be used to identify an object within a group of objects

offset: F | None

Optional offset, in quarternotes. Specifies the start time relative to its parent

It can be None, which indicates that within a container this object would start after the previous object. For an object without a parent, the offset is an absolute offset.

parent

The parent of this object.

This attribute is set by the parent when an object is added to it. For example, when adding a Note to a Chain, the Chain is set as the parent of the Note. This enables the Note to query information about the parent, like its absolute position or if a score structure has been set upstream

playargs: PlayArgs | None

playargs are set via setPlay() and are used to customize playback (instr, gain, …). None by default

properties: dict[str, _t.Any] | None

User-defined properties as a dict (None by default). Set them via setProperty()

symbols: list[_symbols.Symbol] | None

A list of all symbols added via addSymbol() (None by default)

Methods Documentation

absEnd()[source]

Returns the absolute end of this offset, as quarternotes

If this object is embedded (has a parent) in a container, its absolute end depends on the offset of its parent, recursively. If the object has no parent then the absolute offset is just the resolved offset

Return type:

Fraction

Returns:

the absolute end position of this object

absOffset()[source]

Returns the absolute offset of this object in quarternotes

If this object is embedded (has a parent) in a container, its absolute offset depends on the offset of its parent, recursively. If the object has no parent then the absolute offset is just the resolved offset

Return type:

Fraction

Returns:

the absolute start position of this object

activeScorestruct()[source]

Returns the ScoreStruct active for this obj or its parent.

Otherwise returns the scorestruct for the active workspace

Return type:

ScoreStruct

Returns:

the active scorestruct for this object

addSymbol(*args, **kws)[source]

Add a notation symbol to this object

Some symbols are exclusive, meaning that adding a symbol of this kind will replace a previously set symbol. Exclusive symbols include any properties (color, size, etc) and other customizations like notehead shape

Example

>>> from maelzel.core import *
>>> n = Note(60)
>>> n.addSymbol(symbols.Articulation('accent'))
# The same can be achieved via keyword arguments:
>>> n.addSymbol(articulation='accent')
# Multiple symbols can be added at once:
>>> n = Note(60).addSymbol(text='dolce', articulation='tenuto')
>>> n2 = Note("4G").addSymbol(symbols.Articulation('accent'), symbols.Ornament('mordent'))
# Known symbols - most common symbols don't actually need keyword arguments:
>>> n = Note("4Db").addSymbol('accent').addSymbol('fermata')
# Some symbols can take customizations:
>>> n3 = Note("4C+:1/3").addSymbol(symbols.Harmonic(interval='4th'))
Return type:

Self

Returns:

self (similar to setPlay, allows to chain calls)

addText(text, placement='above', italic=False, weight='normal', fontsize=None, fontfamily='', box='')[source]

Add a text annotation to this object

This is a shortcut to self.addSymbol(symbols.Text(...)). Use that for in-depth customization.

Parameters:
  • text (str) – the text annotation

  • placement – where to place the annotation (‘above’, ‘below’)

  • italic – if True, use italic as font style

  • weight – ‘normal’ or ‘bold’

  • fontsize (int | None) – the size of the annotation

  • fontfamily – the font family to use. It is probably best to leave this unset

  • box – the enclosure shape, or ‘’ for no box around the text. Possible shapes are ‘square’, ‘circle’, ‘rounded’

Return type:

Self

Returns:

self. This can be used to create an object and add text in one call

Example

>>> chain = Chain([
...     Note("4C", 1).addText('do'),
...     Note("4D", 1).addText('re')
... ])
>>> chain
api/assets/event-addText.png
clone(**kws)[source]

Clone this object, changing parameters if needed

Parameters:

**kws – any keywords passed to the constructor

Return type:

Self

Returns:

a clone of this object, with the given arguments changed

Example:

>>> from maelzel.core import *
>>> a = Note("C4+", dur=1)
>>> b = a.clone(dur=0.5)
copy()[source]

Returns a copy of this object

Return type:

Self

dump(indents=0, forcetext=False)[source]

Prints all relevant information about this object

Parameters:
  • indents – number of indents

  • forcetext – if True, force text output via print instead of html even when running inside jupyter

durSecs()[source]

Returns the duration in seconds according to the active score

Return type:

Fraction

Returns:

the duration of self in seconds

getConfig(prototype=None)[source]

Returns a CoreConfig overloaded with options set for this object

Parameters:

prototype (Optional[CoreConfig]) – the config to use as prototype, falls back to the active config

Return type:

CoreConfig | None

Returns:

A clone of the active config with any customizations made via Voice.setConfig() or Voice.configQuantization() If no customizations have been made, None is returned

getPlay(key, default=None, recursive=True)[source]

Get a playback attribute previously set via MObj.setPlay()

All locally set playback attributes are accessible via the MEvent.playargs attribute. This method checks not only the locally set attributes, but any attribute set by the parent

Parameters:
  • key (str) – the key (see setPlay for possible keys)

  • default – the value to return if the given key has not been set

  • recursive – if True, search the given attribute up the parent chain

Returns:

either the value previously set, or default otherwise.

getProperty(key, default=None)[source]

Get a property of this objects

An MObj can have multiple properties. A property is a key:value pair, where the key is a string and the value can be anything. Properties can be used to attach information to an object, to tag it in any way needed.

Properties are set via MObj.setProperty(). The MObj.properties attribute can be queries directly, but bear in mind that if no properties have been set, this attribute is ``None`` by default.

Parameters:
  • key (str) – the property to query

  • default – returned value if the property has not been set

Returns:

the value of the property, or the default value

getSymbol(classname)[source]

Get a symbol of a given class, if present

This is only supported for symbol classes which are exclusive (notehead, color, ornament, etc.). For symbols like ‘articulation’, which can be present multiple times, query the symbols attribute directly (NB: symbols might be None if no symbols have been set):

if note.symbols:
    articulations = [s for s in note.symbols
                     if s.name == 'articulation']
Parameters:

classname (str) – the class of the symbol. Possible values are ‘articulation’, ‘text’, ‘notehead’, ‘color’, ‘ornament’, ‘fermata’, ‘notatedpitch’. See XXX (TODO) for a complete list

Return type:

_symbols.Symbol | None

Returns:

a symbol of the given class, or None

invertPitch(pivot)[source]

Invert the pitch of this object

Parameters:

pivot (str | float | int) – the point around which to invert pitches

Return type:

Self

Returns:

the inverted object

>>> from maelzel.core import *
>>> series = Chain("4Bb 4E 4F# 4Eb 4F 4A 5D 5C# 4G 4G# 4B 5C".split())
>>> inverted = series.invertPitch("4F#")
>>> print(" ".join(_.name.ljust(4) for _ in series))
... print(" ".join(_.name.ljust(4) for _ in inverted))
4A#  4E   4F#  4D#  4F   4A   5D   5C#  4G   4G#  4B   5C
4D   4G#  4F#  4A   4G   4D#  3A#  3B   4F   4E   4C#  4C
>>> Score([series, inverted])
../_images/dodecaphonic-series-1-inverted.png
isRest()[source]

Is this object a Rest?

Rests are used as separators between objects inside an Chain or a Track

Return type:

bool

location()[source]

Returns the location of this object within the active score struct

Return type:

tuple[location_t, location_t]

Returns:

a tuple (startlocation, endlocation) where both startlocation are tuples (measureindex, beatoffset) representing the position of this object within the score

Example

>>> setScoreStruct(timesig='3/4')
>>> note = Note("4C", 1, offset=5)
>>> note.location()
((1, Fraction(2, 1)), (2, Fraction(0, 1)))

The note starts at measure 1, beat 2 and ends at measure 2, beat 0 (both measures and beats start at 0)

meanPitch()[source]

The mean pitch of this object

Return type:

float | None

Returns:

The mean pitch of this object

parentAbsOffset()[source]

The absolute offset of the parent

Return type:

Fraction

Returns:

the absolute offset of the parent if this object has a parent, else 0

pitchRange()[source]

The pitch range of this object, if applicable

This is useful in order to assign this object to a proper Voice when distributing objects among voices

Return type:

tuple[float, float] | None

Returns:

either None or a tuple (lowest pitch, highest pitch)

pitchTransform(pitchmap)[source]

Apply a pitch-transform to this object, returns a copy

Parameters:

pitchmap (_t.Callable[[float], float]) – a function mapping pitch to pitch

Return type:

Self

Returns:

the object after the transform

play(instr='', delay=None, args=None, gain=None, chan=None, pitchinterpol='', fade=None, fadeshape='', position=None, skip=None, end=None, whenfinished=None, sustain=None, workspace=None, transpose=0, config=None, display=False, **kwargs)[source]

Plays this object.

Play is always asynchronous (to block, use some sleep funcion). By default, play() schedules this event to be renderer in realtime.

Note

To record events offline, see the example below

Parameters:
  • gain (float | None) – modifies the own amplitude for playback/recording (0-1)

  • delay (float | None) – delay in seconds, added to the start of the object As opposed to the .offset attribute of each object, which is defined in symbolic (beat) time, the delay is always in real (seconds) time. Delay can be negative, in which case synth events start the given amount of seconds earlier.

  • instr – which instrument to use (see defPreset, definedPresets). Use “?” to select from a list of defined presets.

  • chan (int | None) – the channel to output to. Channels start at 1

  • pitchinterpol – ‘linear’, ‘cos’, ‘freqlinear’, ‘freqcos’

  • fade (float | tuple[float, float] | None) – fade duration in seconds, can be a tuple (fadein, fadeout)

  • fadeshape – ‘linear’ | ‘cos’

  • args (dict[str, float] | None) – arguments passed to the note. A dict {paramName: value}

  • position (float | None) – the panning position (0=left, 1=right)

  • skip (float | None) – amount of time (in quarternotes) to skip. Allows to play a fragment of the object (NB: this trims the playback of the object. Use delay to offset the playback in time while keeping the playback time unmodified)

  • end (float | None) – end time of playback. Allows to play a fragment of the object by trimming the end of the playback

  • sustain (float | None) – a time added to the playback events to facilitate overlapping/legato between notes, or to allow one-shot samples to play completely without being cropped.

  • workspace (Workspace | None) – a Workspace. If given, overrides the current workspace. It’s scorestruct is used to to determine the mapping between beat-time and real-time.

  • transpose (float) – add a transposition interval to the pitch of this object

  • config (CoreConfig | None) – if given, overrides the current config

  • whenfinished (_t.Callable | None) – function to be called when the playback is finished. Only applies to realtime rendering

  • display – if True and running inside Jupyter, display the resulting synth’s html

Return type:

csoundengine.synth.SynthGroup

Returns:

A SynthGroup

Example

Play a note

>>> from maelzel.core import *
>>> note = Note(60).play(gain=0.1, chan=2)

Play multiple objects synchronised

>>> play(
... Note(60, 1.5).synthEvents(gain=0.1, position=0.5)
... Chord("4E 4G", 2, start=1.2).synthEvents(instr='piano')
... )

Or using play as a context managger:

>>> with play():
...     Note(60, 1.5).play(gain=0.1, position=0.5)
...     Chord("4E 4G", 2, start=1.2).play(instr='piano')
...     ...

Render offline

>>> with render("out.wav", sr=44100) as r:
...     Note(60, 5).play(gain=0.1, chan=2)
...     Chord("4E 4G", 3).play(instr='piano')
plot(axes=None, figsize=(15, 5), timeSignatures=True, grid=True, **kws)[source]

Plot this object

To see all supported options, see maelzel.core.plotting.plotVoices()

Parameters:
  • axes (Axes | None) – use this Axes, if given

  • figsize (tuple[int, int]) – figure size of the plot, if not axes is given (otherwise uses the figure corresponding to the given axes)

  • timeSignatures – draw time signatures

  • grid – draw a grid

  • kws – passed to maelzel.core.plotting.plotVoices

Return type:

Axes

Returns:

the axes used

quantizePitch(step=0.0)[source]

Returns a new object, with pitch rounded to step

Parameters:

step – quantization step, in semitones. A value of 0 used the default semitone division in the active config (can be configured via getConfig()['semitoneDivisions']

Return type:

Self

Returns:

a copy of self with the pitch quantized

quantizedScore(scorestruct=None, config=None, quantizationProfile=None, enharmonicOptions=None, nestedTuplets=None)[source]

Returns a QuantizedScore representing this object

Parameters:
  • scorestruct (ScoreStruct | None) – if given it will override the scorestructure active for this object

  • config (CoreConfig | None) – if given will override the active config

  • quantizationProfile (str | quant.QuantizationProfile | None) – if given it is used to customize the quantization process. Otherwise, a profile is constructed based on the config. It is also possible to pass the name of a quantization preset (possible values: ‘lowest’, ‘low’, ‘medium’, ‘high’, ‘highest’, see maelzel.scoring.quant.QuantizationProfile.fromPreset())

  • enharmonicOptions (enharmonics.EnharmonicOptions | None) – if given it is used to customize enharmonic respelling. Otherwise, the enharmonic options used for respelling are constructed based on the config

  • nestedTuplets (bool | None) – if given, overloads the config value ‘quant.nestedTuplets’. This is used to disallow nested tuplets, mainly for rendering musicxml since there are some music editors (MuseScore, for example) which fail to import nested tuplets. This can be set at the config level as getConfig()['quant.nestedTuplets'] = False

Return type:

quant.QuantizedScore

Returns:

a quantized score. To render such a quantized score as notation call its render() method

A QuantizedScore contains a list of QuantizedParts, which each consists of list of QuantizedMeasures. To access the recursive notation structure of each measure call its asTree() method

rec(outfile='', sr=0, verbose=None, wait=None, nchnls=None, instr='', delay=None, args=None, gain=None, position=None, extratime=None, workspace=None, **kws)[source]

Record the output of .play as a soundfile

Parameters:
  • outfile – the outfile where sound will be recorded. Can be None, in which case a filename will be generated. Use ‘?’ to open a save dialog

  • sr (int) – the sampling rate (config key: ‘rec.sr’)

  • wait (bool | None) – if True, the operation blocks until recording is finishes (config ‘rec.block’)

  • nchnls (int | None) – if given, use this as the number of channels to record.

  • gain (float | None) – modifies the own amplitude for playback/recording (0-1)

  • delay (float | None) – delay in seconds, added to the start of the object As opposed to the .start attribute of each object, which is defined in symbolic (beat) time, the delay is always in real (seconds) time

  • instr – which instrument to use (see defPreset, definedPresets). Use “?” to select from a list of defined presets.

  • args (dict[str, float] | None) – named arguments passed to the note. A dict {paramName: value}

  • position (float | None) – the panning position (0=left, 1=right)

  • workspace (Workspace | None) – if given it overrides the active workspace

  • extratime (float | None) – extratime added to the recording (config key: ‘rec.extratime’)

  • verbose (bool | None) – if True, display synthesis output

  • **kws – any keyword passed to .play

Return type:

offline.OfflineRenderer

Returns:

the offline renderer used. If no outfile was given it is possible to access the renderer soundfile via OfflineRenderer.lastOutfile()

Example

>>> from maelzel.core import *
>>> # a simple note
>>> chord = Chord("4C 4E 4G", dur=8).setPlay(gain=0.1, instr='piano')
>>> renderer = chord.rec(wait=True)
>>> renderer.lastOutfile()
'/home/testuser/.local/share/maelzel/recordings/tmpashdas.wav'

See also

OfflineRenderer

relEnd()[source]

Resolved end of this object, relative to its parent

An object’s offset can be explicit (set in the .offset attributes) or implicit, as calculated from the context of the parent. For example, inside a Chain, the offset of an event depends on the offsets and durations of the objects preceding it.

Note

To calculate the absolute end of an object, use obj.absOffset() + obj.dur

Return type:

Fraction

Returns:

the resolved end of this object, relative to its parent. If this object has no parent, the relative end and the absolute end are the same

relOffset()[source]

Resolve the offset of this object, relative to its parent

If this object has no parent the offset is an absolute offset.

The .offset attribute holds the explicit offset. If this attribute is unset (None) this object might ask its parent to determine the offset based on the durations of any previous objects

Return type:

Fraction

Returns:

the offset, in quarter notes. If no explicit or implicit offset and the object has no parent it returns 0.

See also

absOffset()

remap(deststruct, sourcestruct=None)[source]

Creates a clone, remapping times from source scorestruct to destination scorestruct

The absolute time remains the same

Parameters:
  • deststruct (ScoreStruct) – the destination scorestruct

  • sourcestruct (ScoreStruct | None) – the source scorestructure, or None to use the resolved scoresturct

Return type:

Self

Returns:

a clone of self remapped to the destination scorestruct

render(backend='', renderoptions=None, scorestruct=None, config=None, quantizationProfile='')[source]

Renders this object as notation

First the object is quantized to abstract notation, then it is passed to the backend to render it for the specific format (lilypond, musicxml, …), which is then used to generate a document (pdf, png, …)

Parameters:
  • backend – the backend to use, one of ‘lilypond’, ‘musicxml’. If not given, defaults to the config key ‘show.backend’

  • renderoptions (RenderOptions | None) – the render options to use. If not given, these are generated from the active config

  • scorestruct (ScoreStruct | None) – if given, overrides the scorestruct set within the active Workspace and any scorestruct attached to this object

  • config (CoreConfig | None) – if given, overrides the active config

  • quantizationProfile (str | quant.QuantizationProfile) – if given, it is used to customize the quantization process and will override any config option related to quantization. A QuantizationProfile can be created from a config via maelzel.core.config.CoreConfig.makeQuantizationProfileFromPreset().

Return type:

Renderer

Returns:

a scoring.Renderer. This can be used to write the rendered structure to an image (png, pdf) or as a musicxml or lilypond file.

Example

>>> from maelzel.core import *
>>> voice = Voice(...)
# Render with the settings defined in the config
>>> voice.render()
# Customize the rendering process
>>> from maelzel.scoring.renderer import RenderOptions
>>> from maelzel.scoring.quant import QuantizationProfile
>>> quantprofile = QuantizationProfile.simple(
...     possibleDivisionsByTempo={80: []
...     })
scorestruct()[source]

Returns the ScoreStruct active for this obj or its parent (recursively)

If this object has no parent None is returned. Use activeScorestruct() to always resolve the active struct for this object

Return type:

ScoreStruct | None

Returns:

the associated scorestruct, if set (either directly or through its parent)

Example

>>> from maelzel.core import *
>>> n = Note("4C", 1)
>>> voice = Voice([n])
>>> score = Score([voice])
>>> score.setScoreStruct(ScoreStruct(timesig=(3, 4), tempo=72))
>>> n.scorestruct()
ScoreStruct(timesig=(3, 4), tempo=72)
scoringEvents(groupid='', config=None, parentOffset=None)[source]

Returns its notated form as scoring.Notations

These can then be converted into notation via some of the available backends: musicxml or lilypond

Parameters:
  • groupid – passed by an object higher in the hierarchy to mark this objects as belonging to a group

  • config (Optional[CoreConfig]) – a configuration to customize rendering

  • parentOffset (Optional[Fraction]) – if given this should be the absolute offset of this object’s parent

Return type:

list[Notation]

Returns:

A list of scoring.Notation which best represent this object as notation

scoringParts(config=None)[source]

Returns this object as a list of scoring UnquantizedParts.

Parameters:

config (Optional[CoreConfig]) – if given, this config instead of the active config will be used

Return type:

list[UnquantizedPart]

Returns:

a list of unquantized parts

This method is used internally to generate the parts which constitute a given MObj prior to rendering, but might be of use itself so it is exposed here.

An maelzel.scoring.UnquantizedPart is an intermediate format used by the scoring package to represent notated events. It represents a list of non-simultaneous Notations, unquantized and independent of any score structure

setPlay(**kws)[source]

Set any playback attributes, returns self

Parameters:

**kws – any argument passed to play() (delay, dur, chan, gain, fade, instr, pitchinterpol, fadeshape, params, priority, position).

Return type:

Self

Returns:

self. This allows to chain this to any constructor (see example)

Attribute

Type

Descr

instr

str

The instrument preset to use

delay

float

Delay in seconds, added to the start of the object

chan

int

The channel to output to, channels start at 1

fade

float

The fade time; can also be a tuple (fadein, fadeout)

fadeshape

str

One of ‘linear’, ‘cos’, ‘scurve’

pitchinterpol

str

One of ‘linear’, ‘cos’, ‘freqlinear’, ‘freqcos’

gain

float

A gain factor applied to the amplitud of this object. Dynamic argument (kgain)

position

float

Dynamic argument. Panning position (0=left, 1=right). Dynamic argument (kpos)

skip

float

Skip time of playback; allows to play a fragment of the object. Time in beats relative to the start of the object NB: set the delay to the -skip to start playback at the original time but from the timepoint specified by the skip param

end

float

End time of playback, in beats, relative to the start of the object; counterpart of skip, allow to trim playback of the object

sustain

float

An extra sustain time, in seconds. This is useful for sample based instruments

transpose

float

Transpose the pitch of this object only for playback

glisstime

float

The duration (in beats) of the glissando for events with glissando. A short glisstime can be used for legato playback in non-percusive instruments. Implies gliss. to the next event.

priority

int

The order of evaluation. Events scheduled with a higher priority are evaluated later in the chain

args

dict

Named arguments passed to the playback instrument

gliss

float/ bool

An object can be set to have a playback only gliss. It is equivalent to having a gliss., but the gliss is not displayed as notation.

Example:

# a piano note
>>> from maelzel.core import *
# Create a note with predetermined instr and panning position
>>> note = Note("C4+25", dur=0.5).setPlay(instr="piano", position=1)
# When .play is called, the note will play with the preset instr and position
>>> note.play()
setProperty(key, value)[source]

Set a property, returns self

An MObj can have user-defined properties. These properties are optional: before any property is created the .properties attribute is None. This method creates the dict if it is still None and sets the property.

Parameters:
  • key (str) – the key to set

  • value – the value of the property

Return type:

Self

Returns:

self (similar to setPlay or setSymbol, to allow for chaining calls)

Example

>>> from maelzel.core import *
>>> n = Note("4C", 1)
>>> n.setProperty('foo', 'bar')
4C:1♩
>>> # To query a property do:
>>> n.getProperty('foo')
bar
>>> # Second Method: query the properties attribute directly.
>>> # WARNING: if no properties were set, this attribute would be None
>>> if n.properties:
...     foo = n.properties.get('foo')
...     print(foo)
bar
show(fmt='', external=None, backend='', scorestruct=None, resolution=0, pageSize='', staffSize=None, cents=None, voiceMaxStaves=None, **kws)[source]

Show this as notation.

Parameters:
  • external (bool | None) – True to force opening the image in an external image viewer, even when inside a jupyter notebook. If False, show will display the image inline if inside a notebook environment. To change the default, modify config[‘openImagesInExternalApp’]

  • backend – backend used when rendering to png/pdf. One of ‘lilypond’, ‘musicxml’. If not given, use default (see config[‘show.backend’])

  • fmt – one of ‘png’, ‘pdf’, ‘ly’. None to use default.

  • scorestruct (ScoreStruct | None) – if given overrides the current/default score structure

  • resolution (int) – dpi resolution when rendering to an image, overrides the config key ‘show.pngResolution’

  • pageSize – if given, overrides config ‘show.pageSize’. One of ‘a3’, ‘a4’, …

  • staffSize (float | None) – if given, overrides config ‘show.staffSize’. A value in points (default = 10.)

  • cents (bool | None) – overrides config ‘show.cents’. False to hide cents deviations as text annotation

  • voiceMaxStaves (int | None) – overrides config ‘show.voiceMaxStaves’. Max. number of staves used when expanding a voice to multiple staves

  • kws – any keyword is used to override the config. All options starting with the ‘show.’ prefix can be used directly (see below)

Return type:

None

Useful keywords

kws

Config Option

Description

staffSize

show.staffSize

Size of a staff, in points

spacing

show.spacing

One of normal (traditional spacing), strict (proportional), uniform (proportional)

voiceMaxStaves

show.voiceMaxStaves

Expands any voice to at most this number of staves

autoClefChanges

show.autoClefChanges

Adds automatic clef changes when rendering

clefSimplify

show.clefSimplify

Simplifies automatic clef changes

cents

show.cents

set to False to avoid showing cents deviations as text annotation

glissStemless

show.glissStemless

remove stems from the end note of a gliss

horizontalSpace

show.horizontalSpace

configure proportional spacing (one of “default”, “small”, “medium”, “large”)

pageOrientation

show.pageOrientation

one of “landscape”, “portrait”

pageSize

show.pageSize

one of “a4”, “a3”, …

synthEvents(instr='', delay=None, args=None, gain=None, chan=None, pitchinterpol='', fade=None, fadeshape='', position=None, skip=None, end=None, sustain=None, workspace=None, transpose=0.0, **kwargs)[source]

Returns the SynthEvents needed to play this object

All these attributes here can be set previously via playargs (or using setPlay())

Parameters:
  • gain (Optional[float]) – modifies the own amplitude for playback/recording (0-1)

  • delay (Optional[float]) – delay in seconds, added to the start of the object As opposed to the .offset attribute of each object, which is defined in quarternotes, the delay is always in seconds. It can be negative, in which case synth events start the given amount of seconds earlier.

  • instr – which instrument to use (see defPreset, definedPresets). Use “?” to select from a list of defined presets.

  • chan (Optional[int]) – the channel to output to. Channels start at 1

  • pitchinterpol – ‘linear’, ‘cos’, ‘freqlinear’, ‘freqcos’

  • fade (Union[float, tuple[float, float], None]) – fade duration in seconds, can be a tuple (fadein, fadeout)

  • fadeshape – ‘linear’ | ‘cos’

  • args (Optional[dict[str, float]]) – named arguments passed to the note. A dict {paramName: value}

  • position (Optional[float]) – the panning position (0=left, 1=right)

  • skip (Optional[float]) – start playback at the given beat (in quarternotes), relative to the start of the object. Allows to play a fragment of the object (NB: this trims the playback of the object. Use delay to offset the playback in time while keeping the playback time unmodified)

  • end (Optional[float]) – end time of playback, in quarternotes. Allows to play a fragment of the object by trimming the end of the playback

  • sustain (Optional[float]) – a time added to the playback events to facilitate overlapping/legato between notes, or to allow one-shot samples to play completely without being cropped.

  • workspace (Optional[Workspace]) – a Workspace. If given, overrides the current workspace. It’s scorestruct is used to determine the mapping between beat-time and real-time.

  • transpose (float) – an interval to transpose any pitch

Return type:

list[SynthEvent]

Returns:

A list of SynthEvents (see SynthEvent)

Example

>>> from maelzel.core import *
>>> n = Note(60, dur=1).setPlay(instr='piano')
>>> n.synthEvnets(gain=0.5)
[SynthEvent(delay=0.000, gain=0.5, chan=1, fade=(0.02, 0.02), instr=piano)
 bps 0.000s:  60, 1.000000
     1.000s:  60, 1.000000]
>>> play(n.synthEvents(chan=2))
timeRange()[source]

Returns a tuple (starttime, endtime), in seconds

Return type:

tuple[Fraction, Fraction]

Returns:

a tuple (starttime: F, endtime: F), where starttime and endtime are both absolute times in seconds

timeScale(factor, offset=Fraction(0, 1))[source]

Create a copy with modified timing by applying a linear transformation

Parameters:
  • factor (num_t) – a factor which multiplies all durations and start times

  • offset (num_t) – an offset added to all start times

Return type:

Self

Returns:

the modified object

timeShift(offset)[source]

Return a copy of this object with an added offset

Parameters:

offset (time_t) – a delta time added

Return type:

Self

Returns:

a copy of this object shifted in time by the given amount

timeShiftInPlace(offset)[source]

Shift the time of this by the given offset (inplace)

Parameters:

offset (time_t) – the time delta (in quarterNotes)

Return type:

None

timeTransform(timemap, inplace=False)[source]

Apply a time-transform to this object

Parameters:
  • timemap (_t.Callable[[F], F]) – a function mapping old time to new time

  • inplace – if True changes are applied inplace

Return type:

Self

Returns:

the resulting object (self if inplace)

Note

time is conceived as abstract ‘beat’ time, measured in quarter-notes. The actual time in seconds will be also determined by any tempo changes in the active score structure.

transpose(interval)[source]

Transpose this object by the given interval

Parameters:

interval (int | float) – the interval in semitones

Return type:

Self

Returns:

the transposed object

transposeByRatio(ratio)[source]

Transpose this by a given frequency ratio, if applicable

A ratio of 2 equals to transposing an octave higher.

Parameters:

ratio (float) – the ratio to transpose by

Return type:

Self

Returns:

a copy of this object, transposed by the given ratio

Example

>>> from maelzel.core import *
>>> n = Note("4C")
# A transposition by a ratio of 2 results in a pitch an octave higher
>>> n.transposeByRatio(2)
5C
unquantizedScore(title='')[source]

Create a maelzel.scoring.UnquantizedScore from this object

Parameters:

title – the title of the resulting score (if given)

Return type:

UnquantizedScore

Returns:

the Arrangement representation of this object

An UnquantizedScore is a list of UnquantizedPart, which is itself a list of Notation. It represents a score in which the Notations within each part are not split into measures, nor organized in beats. To generate a quantized score see quantizedScore()

This method is mostly used internally when an object is asked to be represented as a score. In this case, an UnquantizedScore is created first, which is then quantized, generating a QuantizedScore

withExplicitOffset(forcecopy=False)[source]

Copy of self with explicit times

If self already has explicit offset and duration, self itself is returned. If you relie on the fact that this method returns a copy, use forcecopy=True

Parameters:

forcecopy – if forcecopy, a copy of self will be returned even if self already has explicit times

Return type:

Self

Returns:

a clone of self with explicit times

Example

>>> n = None("4C", dur=0.5)
>>> n
4C:0.5♩
>>> n.offset is None
True
# An unset offset resolves to 0
>>> n.withExplicitTimes()
4C:0.5♩:offset=0
# An unset duration resolves to 1 quarternote beat
>>> Note("4C", offset=2.5).withExplicitTimes()
4C:1♩:offset=2.5
write(outfile, backend='', resolution=0, format='')[source]

Export to multiple formats

Formats supported: pdf, png, musicxml (extension: .xml or .musicxml), lilypond (.ly), midi (.mid or .midi) and pickle

To configure any options either modify the active config or use setConfig() for self. You can also use a config as context manager to temporary change the active config

Parameters:
  • outfile (str) – the path of the output file. The extension determines the format. Formats available are pdf, png, lilypond, musicxml, midi, csd and pickle.

  • backend – the backend used when writing as pdf or png. If not given, the default defined in the active config is used (key: ‘show.backend’). Possible backends: lilypond; musicxml (uses MuseScore to render musicxml as image so MuseScore needs to be installed)

  • resolution (int) – image DPI (only valid if rendering to an image) - overrides the config key ‘show.pngResolution’

  • format – the format to write to. If not given, the format is inferred from the extension of the output file. If the extension is not recognized, an error is raised. One of ‘pdf’, ‘png’, ‘lilypond’, ‘musicxml’, ‘midi’, ‘csd’, ‘pickle’.

Return type:

None

Formats

  • pdf, png: will render the object as notation and save that to the given format

  • lilypond: .ly extension. Will render the object as notation and save it as lilypond text

  • midi: .mid or .midi extension. At the moment this is done via lilypond, so the midi

    produced follows the quantization process used for rendering to notation. Notice that midi cannot reproduce many features of a maelzel object, like microtones, and many complex rhythms will not be translated correctly

  • pickle: the object is serialized using the pickle module. This allows to load it

    via pickle.load: myobj = pickle.load(open('myobj.pickle'))

Example

chain = Chain(...)
with CoreConfig({'show.voiceMaxStaves': 2, 'show.staffSize': 12}):
    chain.write('chain.pdf')