mesonic package#

Subpackages#

Submodules#

mesonic.buffer module#

class mesonic.buffer.Buffer(context: Context, buffer_info: BufferInfo)[source]#

Bases: object

A Buffer represents a data section that is accessible by the Backend.

This can be used to store samples and other audio or other data.

Parameters:
  • context (Context) – The Context of this Buffer.

  • buffer_info (BufferInfo) – Information about the Buffer.

property channel_count: int#

Number of channels of the Buffer.

Type:

int

property context: Context#

The Context of this Buffer.

Type:

Context

property duration: float#

Duration in secounds (frame_count / sr) of the Buffer.

Type:

float

property frame_count: int#

Number of frames in the Buffer.

Type:

int

property sample_count: int#

Number of samples (frames x channels) in the Buffer.

Type:

int

property shape: Tuple[int, int]#

Shape (channel_count, frame_count) of the Buffer.

Type:

Tuple[int, int]

property sr: int#

Sampling rate of the Buffer.

Type:

int

class mesonic.buffer.BufferInfo(frame_count: int, channel_count: int, sr: int)[source]#

Bases: NamedTuple

Information about a Buffer.

channel_count: int#

Alias for field number 1

frame_count: int#

Alias for field number 0

sr: int#

Alias for field number 2

mesonic.context module#

class mesonic.context.Context(backend: Backend)[source]#

Bases: object

Context class that offers a central user interface.

It holds the timeline and all Managers for creating Synths, Records and Buffers. The Managers available can be seen using Context.managers and can also be accessed by the name f.e. Context.synths for the SynthManager.

The Context collects the Events created by the managed Objects and inserts them into the timeline.

Parameters:

backend (Backend) – The Backend for this Context

add_manager(name: str, manager: Manager)[source]#

Add a Manager

This will also add the respective EventHandler and a property with the name.

Parameters:
  • name (str) – Name of the Manager

  • manager (Manager) – Manager instance

at(time: float, info: Dict | None = None)[source]#

Context Manager for scheduling Event at specified time.

Parameters:
  • time (float) – Timepoint for Timeline at which the Events happen.

  • info (Optional[Dict], optional) – Additional information that will be added to all Events scheduled, by default None

Examples

>>> with context.at(2.0) as timepoint:
...     synth.start()
Raises:

RuntimeError – If scheduling Context Managers are nested.

property backend: Backend#

the corresponding Backend for this Context

Type:

Backend

close()[source]#

Close this context.

This will remove this Context instance from the Backend. The context must not be used after calling this method.

create_playback(**playback_kwargs) Playback[source]#

Create a Playback instance.

This playback the Context.timeline using the Context.processor as processor

Returns:

created Playback

Return type:

Playback

disable_realtime() Playback[source]#

Stop the realtime Playback.

Returns:

realtime Playback instance of this Contxt.

Return type:

Playback

enable_realtime(at: float = 0, rate: float = 1) Playback[source]#

Start the realtime Playback.

Parameters:
  • at (float, optional) – starting time of the playback, by default 0

  • rate (float, optional) – starting rate of the playback, by default 1

Returns:

realtime Playback instance of this Context.

Return type:

Playback

event_handlers: List[EventHandler]#

List of the EventHandlers of the Managers

property is_realtime: bool#

Flag if this is in realtime mode.

Type:

bool

managers: Dict[str, Manager]#

Dict with Managers where their names are the key and the instance the value.

now(delay: float = 0.0, info: Dict | None = None)[source]#

Context Manager for scheduling Events now (with delay).

This is useful for grouping Events like demonstrated in the Example.

Parameters:
  • delay (float, default 0.0) – Amount of latency.

  • info (Optional[Dict], optional) – Additional information that will be added to all Events scheduled, by default None

Examples

>>> with context.now() as timepoint:
...     synth1.start()
...     synth2.start()
Raises:

RuntimeError – If used not in realtime mode.

receive_event(event: Event, time: float | None = None)[source]#

Let the context receive an Event

This will insert the Event with respect to the current

Parameters:
  • event (Event) – An Event

  • time (Optional[float]) – Optional time of the event. If None it will try to use the current Context.time Will ignore time when used in scheduling context managers (at/now).

render(output_path=None, **backend_kwargs)[source]#

Render this context in non-realtime using the Backend.

See Context.backend.render_nrt for more information.

Parameters:

output_path (path like) – Output path of the rendering.

render_asig(**backend_kwargs) Asig[source]#

Render this context in non-realtime as Asig using the Backend.

See Context.backend.render_nrt for more information.

reset(at: float | None = None, rate: float | None = None)[source]#

Reset the Context.

This will clear the Context.timeline and stops the Context.playback If Context.is_realtime is True this will restart the Playback instance.

Parameters:
  • at (float, optional) – Timepoint where the Playback will be restarted, by default None

  • rate (float, optional) – Rate for the Playback restart, by default keep current rate

Returns:

playback instance of Context.

Return type:

Playback

stop()[source]#

Stop the current Playbacks and backend audio.

Note that this will not stop the Playbacks.

test(at=0, rate: float | None = None, reset=True)[source]#

Context Manager for scheduling Events with prior reset and playback.start after.

This is useful for repeatedly tweaking and testing your code.

Parameters:
  • at (float, default 0.0) – time where the playback should start.

  • rate (Optional[float], optional) – playback rate, by default None means keep current rate

Examples

You can use >>> with context.test(at=0.5): … with.context.at(1): … synth.start() … with.context.at(2): … synth.stop()

instead of >>> self.context.reset() … with.context.at(1): … synth.start() … with.context.at(2): … synth.stop() … context.playback.start(at=0.5)

Raises:

RuntimeError – If used not in realtime mode.

property time: float#

the current time in seconds.

This respects the is_realtime property.

Type:

float

mesonic.context.DEFAULT_MANGERS = {'buffers': <function <lambda>>, 'records': <function <lambda>>, 'synths': <function <lambda>>}#

Dict containing default managers

Manager names are used as as key and function for thier creation are the values. This should be adjusted if the Backend is extended with more Managers.

Type:

Dict[str, Callable]

mesonic.context.create_context(backend: str | B | Type[B] = 'sc3nb', **backend_kwargs) Context[source]#

Create a Context instance using the provided Backend

Parameters:

backend (Union[str, B, Type[B]], optional) – The backend to be used, by default “sc3nb” See mesonic.backend.start_backend() for more details.

Returns:

The created Context.

Return type:

Context

mesonic.events module#

class mesonic.events.Event(*, track: int = 0, info: Dict = _Nothing.NOTHING)[source]#

Bases: object

Event base class.

info: Dict#

Additional information about this Event.

reverse() Event[source]#

Reverse the Event.

This is useful when executing the Events backwards or reversing/undoing them.

Returns:

reversed Event

Return type:

Event

track: int#

The Timeline track of the Event.

class mesonic.events.GenericEvent(*, track: int = 0, info: Dict = _Nothing.NOTHING, action: Callable, reverse_action: Callable)[source]#

Bases: Event

A Generic Event that has two callables.

action: Callable#

The action to be executed when not reversed

reverse_action: Callable#

The action to be executed when reversed

class mesonic.events.RecordEvent(*, track: int = 0, info: Dict = _Nothing.NOTHING, record: Record, etype: RecordEventType)[source]#

Bases: Event

Event created by a Record instance.

etype: RecordEventType#

The type of RecordEvent.

record: Record#

The respective Record instance.

class mesonic.events.RecordEventType(value)[source]#

Bases: Enum

SynthEventTypes describes what different SynthEvents are possible.

PAUSE = 2#
RESUME = -2#
START = 1#
STOP = -1#
reverse() RecordEventType[source]#

Reverse the RecordEventType

START <-> STOP PAUSE <-> RESUME

Returns:

the reversed RecordEventType

Return type:

RecordEventType

class mesonic.events.SynthEvent(*, track: int = 0, info: Dict = _Nothing.NOTHING, synth: Synth, etype: SynthEventType, data: Dict = _Nothing.NOTHING)[source]#

Bases: Event

Events created by a Synth instance.

data: Dict#

Information about the SynthEvent.

etype: SynthEventType#

The type of SynthEvent.

reverse() SynthEvent[source]#

Reverse the SynthEvent by adjusting the etype and data.

Returns:

the reversed SynthEvent

Return type:

SynthEvent

synth: Synth#

The respective Synth instance.

class mesonic.events.SynthEventType(value)[source]#

Bases: Enum

SynthEventTypes describes what different SynthEvents are possible.

PAUSE = 2#
RESUME = -2#
SET = 0#
START = 1#
STOP = -1#
reverse() SynthEventType[source]#

Reverse the SynthEventType

START <-> STOP PAUSE <-> RESUME SET <-> SET

Returns:

the reversed SynthEventType

Return type:

SynthEventType

mesonic.playback module#

class mesonic.playback.Clock[source]#

Bases: object

The Clock class provides the Time for the Playback.

fast_mode = False#
sleep()[source]#

Sleep according to sleep_time

sleep_time = 0.01#

Clock sleeping time.

time()[source]#

Get the current time.

time_source()#

perf_counter() -> float

Performance counter for benchmarking.

class mesonic.playback.Playback(timeline: Timeline, processor: BundleProcessor, rate: float = 1.0, start: float = 0.0, end: float | None = None, loop: bool = False, loop_duration: float = 1.0, clock: Clock | None = None)[source]#

Bases: object

A Playback for a Timeline.

The Playback processes a Timeline by sending the contained Events to the processor with respect to the provided Clock instance.

The Playback offers the user interactive control over the rate and also allows to jump back and forth.

Parameters:
  • timeline (Timeline) – The Timeline instance for this Playback.

  • processor (BundleProcessor) – The processor that will receive the due Events.

  • rate (float, optional) – The rate of the time, by default 1

  • start (float, optional) – The starting time, by default 0

  • end (Optional[float], optional) – The ending time, by default the timeline.end_time.

  • loop (bool, optional) – Wether the Playback should loop from end to start, by default False

  • loop_duration (float, optional) – The duration between the loop end and start, by default 1

  • clock (Optional[Clock], optional) – The source of time, by default a TimeClock

property end_time: float#

Get the time where Playback will end processing.

The Playback will end processing at this time. By default this will be the timeline.end_time.

However if a value is set explicitly it will be used. To use the timeline.end_time again this should be set to None.

See end_time_offset to learn how this is affected by it.

Returns:

The Time where the Playback will end processing.

Return type:

float

property end_time_offset: float | None#

The offset after the last timeline timestamp.

The end time offset effects the end_time if set to a not None value like this: end_time = timeline.last_timestamp + end_time_offset

Raises:

RuntimeError – If end_time is set manually

Type:

Optional[float]

property loop_end: float#

The loop starting time with respect to reversed state

Type:

float

property loop_start: float#

The loop starting time with respect to reversed state

Type:

float

pause()[source]#

Pause this Playback (set rate = 0).

Raises:

RuntimeError – If Playback is not running.

property paused: bool#

True if this is paused (rate == 0)

Type:

bool

property rate: float#

current Playback rate.

Type:

float

restart(at: float | None = None, rate: float | None = None)[source]#

Restart the Playback by trying to stop and then starting.

Parameters:
  • at (Optional[float], optional) – starting time of the playback, by default self.start_time

  • rate (Optional[float], optional) – starting rate of the playback, by default the last used rate

resume(rate=None)[source]#

Resume the Playback.

Parameters:

rate (_type_, optional) – _description_, by default None

Raises:

RuntimeError – If the Playback was not paused

reverse()[source]#

Reverse the Playback (set rate = -1 * rate) Note that this could need 2 sleep cycles as we access the rate property twice.

property reversed: bool#

True if the Playback is reversed.

Type:

bool

property running: bool#

True if the Playback is running.

Type:

bool

start(at: float | None = None, rate: float | None = None)[source]#

Start the Playback

Parameters:
  • at (Optional[float], optional) – starting time of the playback, by default self.start_time

  • rate (Optional[float], optional) – starting rate of the playback, by default the last used rate

stop()[source]#

Stop the Playback.

Raises:

RuntimeError – If Playback is not running.

property time: float#

current Playback time. Only accessible while running.

Type:

float

mesonic.playback.simple_formatwarning(message, category, filename, lineno, line=None)[source]#

mesonic.processor module#

class mesonic.processor.BundleProcessor(event_handlers: List[EventHandler], latency=0.2)[source]#

Bases: object

The BundleProcessor preprocesses the TimeBundles and sends them to multiple event_handlers.

Parameters:
  • event_handlers (List[EventHandler]) – List of EventHandlers that should handle the TimeBundle contents.

  • latency (float, optional) – the latency that will be added to the scheduled time, by default 0.2

add_handler(handler: EventHandler)[source]#

Add an EventHandler

This will overwrite an old EventHandler if they handle the same Type.

Parameters:

handler (EventHandler) – The new EventHandler.

event_filters: List[Callable[[Event], Event | None]]#

Optional event info filter function. Should return None for filtering. If this is not None all Event will be filtered using this function.

prepare_events(events: List[Event], selected_tracks: List[int] | None = None) List[Event][source]#

Filter and transform Events using the provided filters.

Note that the filters are applied before selecting the Tracks. This means that the function could be used to change the track of an Event prior to the selection of tracks.

Parameters:
  • events (List[Event]) – A list of Events that should be prepared.

  • filters (List[Callable[[Event], Optional[Event]]]) – An a list of filter functions that take an Event and return a transformed Event or None to discard the Event.

  • selected_tracks (Optional[List[int]]) – List of selected tracks, default None If this is not None all Event with a track not in selected_tracks won’t be passed.

Returns:

The list of Events after the transformation.

Return type:

List[Event]

process_bundle(bundle: TimeBundle, scheduled_time: float, reversed: bool, **kwargs) None[source]#

Process the Bundle at the scheduled time according to reversed bool.

Parameters:
  • bundle (TimeBundle) – TimeBundle to process.

  • scheduled_time (float) – Timepoint for which this TimeBundle is scheduled.

  • reversed (bool) – Wether this TimeBundle should be reversed.

selected_tracks: List[int] | None#

Optional list of selected tracks. If this is not None all Event with a track not in selected_tracks won’t be passed.

classmethod split_events(events: List[Event]) Dict[type, List[Event]][source]#

Split events by type

Parameters:

events (List[Event]) – A list of Events.

Returns:

Dictionary with types as keys and belonging Events as value.

Return type:

Dict[type, List[Event]]

mesonic.record module#

class mesonic.record.Record(context: Context, path, track: int = 0)[source]#

Bases: object

A Record allows to save the audio to a file.

Parameters:
  • context (Context) – The Context in which this Record happens.

  • path (path like) – Path where the record should be stored.

  • track (int, optional) – On which Timeline track the RecordEvents should be created, by default 0

property finished: bool#

Wether the record has been finished.

Type:

bool

property path#

The path where this Record will be stored.

Type:

pathlike

pause(info=None)[source]#

Pause the Record.

Parameters:

info (Any, optional) – Additional information about the Event, by default None

Raises:

RuntimeError – If the RecordState is not RUNNING.

resume(info=None)[source]#

Resume the Record.

Parameters:

info (Any, optional) – Additional information about the Event, by default None

Raises:

RuntimeError – If the RecordState is not PAUSED.

start(info=None)[source]#

Start the Record.

Parameters:

info (Any, optional) – Additional information about the Event, by default None

Raises:

RuntimeError – If the RecordState is not PREPARED.

stop(info=None)[source]#

Stop the Record.

Parameters:

info (Any, optional) – Additional information about the Event, by default None

Raises:

RuntimeError – If the RecordState is not RUNNING.

to_asig() Asig[source]#

Transform this record into an pya.Asig.

Returns:

Asig of the record.

Return type:

Asig

Raises:
class mesonic.record.RecordState(value)[source]#

Bases: Enum

The different States of the Record

PAUSED = 3#
PREPARED = 1#
RUNNING = 2#
STOPPED = 4#

mesonic.synth module#

class mesonic.synth.Parameter(synth: Synth, name: str, default, min_value=None, max_value=None)[source]#

Bases: object

A Parameter of a Synth.

Parameters:
  • synth (Synth) – The Synth to which this Parameter belongs.

  • name (str) – The name of the Parameter.

  • default (Any) – The default Paramter value.

  • min_value (Any, optional) – The min value possible for this Parameter, by default None None means there is no check.

  • max_value (Any, optional) – The max value possible for this Parameter, by default None None means there is no check.

property bounds: Tuple[Any, Any]#

The bounds (min, max) of the Parameter

property default#

Default value of the Parameter.

property max: Any#

Maximum allowed value of the Parameter. If it is None there is no check when setting.

property min: Any#

Maximum allowed value of the Parameter. If it is None there is no check when setting.

property name: str#

The Paramter name.

Type:

str

set(value, info=None)[source]#

Set the Parameter value.

Parameters:
  • value (Any) – The new Parameter value.

  • info (Any) – Additional information about the Event.

property value: Any#

The Parameter value. If no explicit value is set return the default Paramter value. Setting value is the same as using the set method.

class mesonic.synth.ParameterInfo(name: str, default: Any)[source]#

Bases: object

default: Any#
max_value = None#
min_value = None#
name: str#
class mesonic.synth.Synth(context: Context, name: str, mutable: bool, param_info: List[ParameterInfo], track: int = 0, metadata: Dict | None = None)[source]#

Bases: object

A controllable audio source.

Parameters:
  • context (Context) – Context for this Synth

  • name (str) – name of this Synth

  • mutable (bool) – True if this Synth is mutable

  • param_info (List[ParameterInfo]) – Parameter information of the Synth

  • track (int, optional) – track of the Synth, by default 0

  • metadata (Optional[Dict], optional) – additional metadata, by default None

property context: Context#

Context in which the Synth happens.

Type:

Context

property mutable: bool#

True if this is a mutable Synth.

Type:

bool

property name: str#

name of the Synth.

Type:

str

property params: Dict[str, Parameter]#

The Parameters of this Synths.

Type:

Dict[str, “Parameter”]

pause(info=None)[source]#

Pause the Synth.

Parameters:

info (Any, optional) – Additional information about the Event, by default None, by default None

resume(info=None)[source]#

Resume the Synth.

Parameters:

info (Any, optional) – Additional information about the Event, by default None, by default None

set(params: Dict[str, Any] | None = None, info=None, **kwargs)[source]#

Set the Parameters of the Synth.

Parameters:
  • params (Optional[Dict[str, Any]], optional) – A dict with (name, value) pairs for the Parameters.

  • info (Any, optional) – Additional information about the Event, by default None, by default None

  • kwargs (Any, optional) – Additional keyword arguments are added to params.

start(params: Dict[str, Any] | None = None, info=None, **kwargs)[source]#

Start the Synth.

Parameters:
  • params (Optional[Dict[str, Any]], optional) – A dict with (name, value) pairs for the Parameters, by default None

  • info (Any, optional) – Additional information about the Event, by default None, by default None

  • kwargs (Any, optional) – Additional keyword arguments are added to params.

stop(info=None)[source]#

Stop the Synth.

Parameters:

info (Any, optional) – Additional information about the Event, by default None, by default None

property track: int#

track of the Synth.

Type:

int

mesonic.timeline module#

class mesonic.timeline.TimeBundle(timestamp: float, prev: TimeBundle, next: TimeBundle, events: List[Event] = _Nothing.NOTHING)[source]#

Bases: object

A Bundle of Events with a timestamp.

events: List[Event]#
next: TimeBundle#
prev: TimeBundle#
timestamp: float#
class mesonic.timeline.Timeline[source]#

Bases: object

A sorted double linked list with TimeBundles.

after(time: float) TimeBundle[source]#

Get the TimeBundle after the provided time.

Parameters:

time (float) – Time that must be before the returned TimeBundle timestamp.

Returns:

The TimeBundle after the provided time.

Return type:

TimeBundle

Raises:

ValueError – If the Timeline is empty or the Timeline ends before the time.

before(time: float) TimeBundle[source]#

Get the TimeBundle before the provided time.

Parameters:

time (float) – Time that must be after the returned TimeBundle timestamp.

Returns:

The TimeBundle before the provided time.

Return type:

TimeBundle

Raises:

ValueError – If the Timeline is empty or the Timeline ends before the time.

property end_time: float#

end_time of this Timeline

If not explicitly set this is end_time = last_timestamp + end_time_offset

Type:

float

property end_time_offset: float | None#

The offset after the last timestamp

The end time offset effects the end_time if set to a not None value like this: end_time = timeline.last_timestamp + end_time_offset

Raises:

RuntimeError – If end_time is set manually

Type:

Optional[float]

extend(timeline: Dict[float, List[Event]], timeshift: float = 0, fun: Callable[[Event], Event | None] | None = None)[source]#

Extend this Timeline by a dict containing times and Events

Parameters:
  • timeline (Dict[float, List[Event]]) – dict with events and times.

  • timeshift (float, optional) – time value that will be added to all times, by default 0

  • fun (Optional[Callable[[Event], Optional[Event]]]) – An optional function that takes an Event and returns a transformed Event or None to discard the Event. This will be applied to all the Events that are added.

filter(predicate: Callable[[Event], bool])[source]#

Filter Events that don’t return true if predicate is applied.

If a TimeBundle has no events after filtering it will be removed.

Parameters:

predicate (Callable[[Event], bool]) – Function used to filter the events.

property first_timestamp: float#

first timestamp in this Timeline

Type:

float

insert(time: float, events: List[Event])[source]#

Insert the Events into the Timeline.

Parameters:
  • time (float) – Time where the Events should be inserted.

  • events (List[Event]) – Events to be inserted.

Raises:

ValueError – If the time is not finite.

is_empty() bool[source]#

Test if this Timeline is empty.

Returns:

True if empty.

Return type:

bool

property last_timestamp: float#

last timestamp in this Timeline

Type:

float

plot(duration_key='dur', default_duration=0.1)[source]#

Plot the Timeline.

Parameters:
  • duration_key (str, optional) – The Parameter name for the Synth duration, by default “dur” This is used to extract the duration from the Events.

  • default_duration (float, optional) – The fallback value if no duration can be found, by default 0.1

Raises:

ImportError – If matplotlib cannot be imported.

reset()[source]#

Reset this Timeline by removing all Events.

search_at(at: float, direction_reversed: bool) Tuple[TimeBundle | None, bool][source]#

Search a next TimeBundle at the provided time.

If there is no TimeBundle after/before the provided time it will fallback to the tail/head of the Timeline if available.

Parameters:
  • at (float) – At which timepoint the search starts.

  • direction_reversed (bool) – True to search forward, False for backwards.

Returns:

The TimeBundle or None if the Timeline is empty The bool

Return type:

Tuple[Optional[TimeBundle], bool]

to_dict(timeshift: float = 0) Dict[float, List[Event]][source]#

Transform this Timeline into a dict.

Parameters:
  • timeshift (float, optional) – time value that will be added to all times, by default 0

  • events. (The timestamps are the keys and the values the lists of) –

Returns:

This Timeline as dict.

Return type:

Dict[float, List[Event]]

class mesonic.timeline.TimelineEnumerator(timeline)[source]#

Bases: object

A Enumerator for the Timeline

Module contents#

The mesonic package provides classes and functions for using the mesonic framework.

mesonic.create_context(backend: str | B | Type[B] = 'sc3nb', **backend_kwargs) Context[source]#

Create a Context instance using the provided Backend

Parameters:

backend (Union[str, B, Type[B]], optional) – The backend to be used, by default “sc3nb” See mesonic.backend.start_backend() for more details.

Returns:

The created Context.

Return type:

Context