sc3nb

Package for interfacing SuperCollider.

Collection of Classes and functions for communicating with SuperCollider within python and jupyter notebooks, as well as playing recording and visualizing audio.

Examples

For example usage please refer to the user guide.

Package Contents

Function List

startup

Inits SuperCollider (scsynth, sclang) and registers ipython magics

Class List

SC

Create a SuperCollider Wrapper object.

SCServer

SuperCollider audio server representaion.

ServerOptions

Options for the SuperCollider audio server

SCLang

Class to control the SuperCollider Language Interpreter (sclang).

Node

Representation of a Node on SuperCollider.

Synth

Representation of a Synth on SuperCollider.

Group

Representation of a Group on SuperCollider.

AddAction

AddAction of SuperCollider nodes.

SynthDef

Wrapper for SuperCollider SynthDef

Buffer

A Buffer object represents a SuperCollider3 Buffer on scsynth

Bus

Represenation of Control or Audio Bus(es) on the SuperCollider Server

Score

Recorder

Allows to record audio easily.

TimedQueue

Accumulates events as timestamps and functions.

TimedQueueSC

Timed queue with OSC communication.

OSCMessage

Class for creating messages to send over OSC

Bundler

Class for creating OSCBundles and bundling of messages

Content

sc3nb.startup(start_server: bool = True, scsynth_path: Optional[str] = None, start_sclang: bool = True, sclang_path: Optional[str] = None, magic: bool = True, scsynth_options: Optional[sc3nb.sc_objects.server.ServerOptions] = None, with_blip: bool = True, console_logging: bool = False, allowed_parents: Sequence[str] = ALLOWED_PARENTS, timeout: float = 10) SC[source]

Inits SuperCollider (scsynth, sclang) and registers ipython magics

Parameters:
start_serverbool, optional

If True boot scsynth, by default True

scsynth_pathOptional[str], optional

Path of scscynth executable, by default None

start_sclangbool, optional

If True start sclang, by default True

sclang_pathOptional[str], optional

Path of sclang executable, by default None

magicbool, optional

If True register magics to ipython, by default True

scsynth_optionsOptional[ServerOptions], optional

Options for the server, by default None

with_blipbool, optional

make a sound when booted, by default True

console_loggingbool, optional

If True write scsynth/sclang output to console, by default False

allowed_parentsSequence[str], optional

Names of parents that are allowed for other instances of sclang/scsynth processes, by default ALLOWED_PARENTS

timeoutfloat, optional

timeout in seconds for starting the executable, by default 10

Returns:
SC

SuperCollider Interface class.

class sc3nb.SC(*, start_server: bool = True, scsynth_path: Optional[str] = None, start_sclang: bool = True, sclang_path: Optional[str] = None, scsynth_options: Optional[sc3nb.sc_objects.server.ServerOptions] = None, with_blip: bool = True, console_logging: bool = True, allowed_parents: Sequence[str] = ALLOWED_PARENTS, timeout: float = 5)[source]

Create a SuperCollider Wrapper object.

Parameters:
start_serverbool, optional

If True boot scsynth, by default True.

scsynth_pathOptional[str], optional

Path of scscynth executable, by default None.

start_sclangbool, optional

If True start sclang, by default True.

sclang_pathOptional[str], optional

Path of sclang executable, by default None.

scsynth_optionsOptional[ServerOptions], optional

Options for the server, by default None.

with_blipbool, optional

Make a sound when booted, by default True.

console_loggingbool, optional

If True write scsynth/sclang output to console, by default True.

allowed_parentsSequence[str], optional

Names of parents that are allowed for other instances of sclang/scsynth processes, by default ALLOWED_PARENTS.

timeoutfloat, optional

timeout in seconds for starting the executables, by default 5

default: Optional[SC]

Default SC instance.

This will be used by all SuperCollider objects if no SC/server/lang is specified.

Overview:

get_default

Get the default SC instance

start_sclang

Start this SuperCollider language

start_server

Start this SuperCollider server

_try_to_connect

__del__

__repr__

Return repr(self).

exit

Closes SuperCollider and shuts down server

classmethod get_default() SC[source]

Get the default SC instance

Returns:
SC

default SC instance

Raises:
RuntimeError

If there is no default SC instance.

start_sclang(sclang_path: Optional[str] = None, console_logging: bool = True, allowed_parents: Sequence[str] = ALLOWED_PARENTS, timeout: float = 5)[source]

Start this SuperCollider language

Parameters:
sclang_pathOptional[str], optional

Path of sclang executable, by default None

console_loggingbool, optional

If True write scsynth/sclang output to console, by default True

allowed_parentsSequence[str], optional

Names of parents that are allowed for other instances of sclang/scsynth processes, by default ALLOWED_PARENTS

timeoutfloat, optional

timeout in seconds for starting the executable, by default 5

start_server(scsynth_options: Optional[sc3nb.sc_objects.server.ServerOptions] = None, scsynth_path: Optional[str] = None, console_logging: bool = True, with_blip: bool = True, allowed_parents: Sequence[str] = ALLOWED_PARENTS, timeout: float = 5)[source]

Start this SuperCollider server

Parameters:
scsynth_optionsOptional[ServerOptions], optional

Options for the server, by default None

scsynth_pathOptional[str], optional

Path of scscynth executable, by default None

console_loggingbool, optional

If True write scsynth/sclang output to console, by default True

with_blipbool, optional

make a sound when booted, by default True

allowed_parentsSequence[str], optional

Names of parents that are allowed for other instances of sclang/scsynth processes, by default ALLOWED_PARENTS

timeoutfloat, optional

timeout in seconds for starting the executable, by default 5

_try_to_connect()[source]
__del__()[source]
__repr__() str[source]

Return repr(self).

exit() None[source]

Closes SuperCollider and shuts down server

class sc3nb.SCServer(options: Optional[ServerOptions] = None)[source]

Bases: sc3nb.osc.osc_communication.OSCCommunication

SuperCollider audio server representaion.

Parameters

optionsOptional[ServerOptions], optional

Options used to start the local server, by default None

Create an OSC communication server

Parameters:
server_ipstr

IP address to use for this server

server_portint

port to use for this server

default_receiver_ipstr

IP address used for sending by default

default_receiver_portint

port used for sending by default

Overview:

boot

Start the Server process.

init

Initialize the server.

execute_init_hooks

Run all init hook functions.

connect_sclang

Connect sclang to the server

add_init_hook

Create and add a hook to be executed when the server is initialized

remove_init_hook

Remove a previously added init Hook

bundler

Generate a Bundler with added server latency.

blip

Make a blip sound

remote

Connect to remote Server

reboot

Reboot this server

ping

Ping the server.

quit

Quits and tries to kill the server.

sync

Sync the server with the /sync command.

send_synthdef

Send a SynthDef as bytes.

load_synthdef

Load SynthDef file at path.

load_synthdefs

Load all SynthDefs from directory.

notify

Notify the server about this client.

free_all

Free all node ids.

clear_schedule

Send /clearSched to the server.

send_default_groups

Send the default groups for all clients.

mute

Mute audio

unmute

Set volume back to volume prior to muting

version

Server version information

status

Server status information

dump_osc

Enable dumping incoming OSC messages at the server process

dump_tree

Server process prints out current nodes

query_tree

Query all nodes at the server and return a NodeTree

_init_osc_communication

_get_errors_for_address

_log_repr

_log_message

_warn_fail

__repr__

Return repr(self).

boot(scsynth_path: Optional[str] = None, timeout: float = 5, console_logging: bool = True, with_blip: bool = True, kill_others: bool = True, allowed_parents: Sequence[str] = ALLOWED_PARENTS)[source]

Start the Server process.

Parameters:
scsynth_pathstr, optional

Path of scscynth executable, by default None

timeoutfloat, optional

Timeout for starting the executable, by default 5

console_loggingbool, optional

If True write process output to console, by default True

with_blipbool, optional

make a sound when booted, by default True

kill_othersbool

kill other SuperCollider server processes.

allowed_parentsSequence[str], optional

Names of parents that are allowed for other instances of scsynth processes that won’t be killed, by default ALLOWED_PARENTS

Raises:
ValueError

If UDP port specified in options is already used

ProcessTimeout

If the process fails to start.

init(with_blip: bool = True)[source]

Initialize the server.

This adds allocators, loads SynthDefs, send default Groups etc.

Parameters:
with_blipbool, optional

make a sound when initialized, by default True

execute_init_hooks() None[source]

Run all init hook functions.

This is automatically done when running free_all, init or connect_sclang.

Hooks can be added using add_init_hook

connect_sclang(port: int) None[source]

Connect sclang to the server

This will add the “sclang” receiver and execute the init hooks

Parameters:
portint

Port of sclang (NetAddr.langPort)

add_init_hook(fun: Callable, *args: Any, **kwargs: Any) Hook[source]

Create and add a hook to be executed when the server is initialized

Parameters:
hookCallable[…, None]

Function to be executed

argsAny, optional

Arguments given to function

kwargsAny, optional

Keyword arguments given to function

Returns:
Hook

The created Hook

remove_init_hook(hook: Hook)[source]

Remove a previously added init Hook

Parameters:
hookHook

the hook to be removed

bundler(timetag=0, msg=None, msg_params=None, send_on_exit=True)[source]

Generate a Bundler with added server latency.

This allows the user to easly add messages/bundles and send it.

Parameters:
timetagfloat

Time at which bundle content should be executed. This servers latency will be added upon this. If timetag <= 1e6 it is added to time.time().

msg_addrstr

SuperCollider address.

msg_paramslist, optional
List of parameters to add to message.

(Default value = None)

Returns:
Bundler

bundler for OSC bundling.

blip() None[source]

Make a blip sound

remote(address: str, port: int, with_blip: bool = True) None[source]

Connect to remote Server

Parameters:
addressstr

address of remote server

portint

port of remote server

with_blipbool, optional

make a sound when initialized, by default True

reboot() None[source]

Reboot this server

Raises:
RuntimeError

If this server is remote and can’t be restarted.

abstract ping()[source]

Ping the server.

quit() None[source]

Quits and tries to kill the server.

sync(timeout=5) bool[source]

Sync the server with the /sync command.

Parameters:
timeoutint, optional
Time in seconds that will be waited for sync.

(Default value = 5)

Returns:
bool

True if sync worked.

send_synthdef(synthdef_bytes: bytes)[source]

Send a SynthDef as bytes.

Parameters:
synthdef_bytesbytes

SynthDef bytes

waitbool

If True wait for server reply.

load_synthdef(synthdef_path: str)[source]

Load SynthDef file at path.

Parameters:
synthdef_pathstr

Path with the SynthDefs

bundlebool

Wether the OSC Messages can be bundle or not. If True sc3nb will not wait for the server response, by default False

load_synthdefs(synthdef_dir: Optional[str] = None, completion_msg: Optional[bytes] = None) None[source]

Load all SynthDefs from directory.

Parameters:
synthdef_dirstr, optional

directory with SynthDefs, by default sc3nb default SynthDefs

completion_msgbytes, optional

Message to be executed by the server when loaded, by default None

notify(receive_notifications: bool = True, client_id: Optional[int] = None, timeout: float = 1) None[source]

Notify the server about this client.

This provides the client id and max logins info needed for default groups.

Parameters:
receive_notificationsbool, optional

Flag for receiving node notification from server, by default True

client_idint, optional

Propose a client id, by default None

timeoutfloat, optional

Timeout for server reply, by default 1.0

Raises:
RuntimeError

If server has too many users.

OSCCommunicationError

If OSC communication fails.

free_all(root: bool = True) None[source]

Free all node ids.

Parameters:
rootbool, optional

If False free only the default group of this client, by default True

clear_schedule()[source]

Send /clearSched to the server.

This clears all scheduled bundles and removes all bundles from the scheduling queue.

send_default_groups() None[source]

Send the default groups for all clients.

mute() None[source]

Mute audio

unmute() None[source]

Set volume back to volume prior to muting

version() ServerVersion[source]

Server version information

status() ServerStatus[source]

Server status information

dump_osc(level: int = 1) None[source]

Enable dumping incoming OSC messages at the server process

Parameters:
levelint, optional

Verbosity code, by default 1 0 turn dumping OFF. 1 print the parsed contents of the message. 2 print the contents in hexadecimal. 3 print both the parsed and hexadecimal representations.

dump_tree(controls: bool = True, return_tree=False) Optional[str][source]

Server process prints out current nodes

Parameters:
controlsbool, optional

If True include control values, by default True

return_treebool, optional

If True return output as string, by default False

Returns:
str

If return_tree this is the node tree string.

query_tree(include_controls: bool = True) sc3nb.sc_objects.node.Group[source]

Query all nodes at the server and return a NodeTree

Parameters:
include_controlsbool, optional

If True include control values, by default True

Returns:
NodeTree

object containing all the nodes.

_init_osc_communication()[source]
_get_errors_for_address(address: str)[source]
_log_repr()[source]
_log_message(sender, *params)[source]
_warn_fail(sender, *params)[source]
__repr__() str[source]

Return repr(self).

class sc3nb.ServerOptions(udp_port: int = SCSYNTH_DEFAULT_PORT, max_logins: int = 6, num_input_buses: int = 2, num_output_buses: int = 2, num_audio_buses: int = 1024, num_control_buses: int = 4096, num_sample_buffers: int = 1024, publish_rendezvous: bool = False, block_size: Optional[int] = None, hardware_buffer_size: Optional[int] = None, hardware_sample_size: Optional[int] = None, hardware_input_device: Optional[str] = None, hardware_output_device: Optional[str] = None, other_options: Optional[Sequence[str]] = None)[source]

Options for the SuperCollider audio server

This allows the encapsulation and handling of the command line server options.

Overview:

__repr__

Return repr(self).

__repr__()[source]

Return repr(self).

class sc3nb.SCLang[source]

Class to control the SuperCollider Language Interpreter (sclang).

Creates a python representation of sclang.

Raises:
NotImplementedError

When an unsupported OS was found.

Overview:

start

Start and initilize the sclang process.

init

Initialize sclang for sc3nb usage.

load_synthdefs

Load SynthDef files from path.

kill

Kill this sclang instance.

__del__

__repr__

Return repr(self).

cmd

Send code to sclang to execute it.

cmdv

cmd with verbose=True

cmds

cmd with verbose=False, i.e. silent

cmdg

cmd with get_result=True

read

Reads SuperCollider output from the process output queue.

empty

Empties sc output queue.

get_synth_description

Get a SynthDesc like description via sclang's global SynthDescLib.

connect_to_server

Connect this sclang instance to the SuperCollider server.

start(sclang_path: Optional[str] = None, console_logging: bool = True, allowed_parents: Sequence[str] = ALLOWED_PARENTS, timeout: float = 10) None[source]

Start and initilize the sclang process.

This will also kill sclang processes that does not have allowed parents.

Parameters:
sclang_pathOptional[str], optional

Path with the sclang executable, by default None

console_loggingbool, optional

If True log sclang output to console, by default True

allowed_parentsSequence[str], optional

parents name of processes to keep, by default ALLOWED_PARENTS

timeoutfloat, optional

timeout in seconds for starting the executable, by default 10

Raises:
SCLangError

When starting or initilizing sclang failed.

init()[source]

Initialize sclang for sc3nb usage.

This will register the /return callback in sclang and load the SynthDefs from sc3nb.

This is done automatically by running start.

load_synthdefs(synthdefs_path: Optional[str] = None) None[source]

Load SynthDef files from path.

Parameters:
synthdefs_pathstr, optional

Path where the SynthDef files are located. If no path provided, load default sc3nb SynthDefs.

kill() int[source]

Kill this sclang instance.

Returns:
int

returncode of the process.

__del__()[source]
__repr__() str[source]

Return repr(self).

cmd(code: str, pyvars: Optional[dict] = None, verbose: bool = True, discard_output: bool = True, get_result: bool = False, print_error: bool = True, get_output: bool = False, timeout: int = 1) Any[source]

Send code to sclang to execute it.

This also allows to get the result of the code or the corresponding output.

Parameters:
codestr

SuperCollider code to execute.

pyvarsdict, optional

Dictionary of name and value pairs of python variables that can be injected via ^name, by default None

verbosebool, optional

If True print output, by default True

discard_outputbool, optional

If True clear output buffer before passing command, by default True

get_resultbool, optional

If True receive and return the evaluation result from sclang, by default False

print_errorbool, optional

If this and get_result is True and code execution fails the output from sclang will be printed.

get_outputbool, optional

If True return output. Does not override get_result If verbose this will be True, by default False

timeoutint, optional

Timeout in seconds for code execution return result, by default 1

Returns:
Any
if get_result=True,

Result from SuperCollider code, not all SC types supported. When type is not understood this will return the datagram from the OSC packet.

if get_output or verbose

Output from SuperCollider code.

if get_output and get_result=True

(result, output)

else

None

Raises:
RuntimeError

If get_result is True but no OSCCommunication instance is set.

SCLangError

When an error with sclang occurs.

cmdv(code: str, **kwargs) Any[source]

cmd with verbose=True

cmds(code: str, **kwargs) Any[source]

cmd with verbose=False, i.e. silent

cmdg(code: str, **kwargs) Any[source]

cmd with get_result=True

read(expect: Optional[str] = None, timeout: float = 1, print_error: bool = True) str[source]

Reads SuperCollider output from the process output queue.

Parameters:
expectOptional[str], optional

Try to read this expected string, by default None

timeoutfloat, optional

How long we try to read the expected string in seconds, by default 1

print_errorbool, optional

If True this will print a message when timed out, by default True

Returns:
str

output from sclang process.

Raises:
timeout

If expected output string could not be read before timeout.

empty() None[source]

Empties sc output queue.

get_synth_description(synth_def)[source]

Get a SynthDesc like description via sclang’s global SynthDescLib.

Parameters:
synth_defstr

SynthDef name

Returns:
dict

{argument_name: SynthArgument(rate, default)}

Raises:
ValueError

When SynthDesc of synth_def can not be found.

connect_to_server(server: Optional[sc3nb.sc_objects.server.SCServer] = None)[source]

Connect this sclang instance to the SuperCollider server.

This will set Server.default and s to the provided remote server.

Parameters:
serverSCServer, optional

SuperCollider server to connect. If None try to reconnect.

Raises:
ValueError

If something different from an SCServer or None was provided

SCLangError

If sclang failed to register to the server.

class sc3nb.Node(*, nodeid: Optional[int] = None, add_action: Optional[Union[AddAction, int]] = None, target: Optional[Union[Node, int]] = None, server: Optional[sc3nb.sc_objects.server.SCServer] = None)[source]

Bases: abc.ABC

Representation of a Node on SuperCollider.

Create a new Node

Parameters:
nodeidint or None

This Nodes node id or None

add_actionAddAction or corresponding int, optional

This Nodes AddAction when created in Server, by default None

targetNode or int or None, optional

This Nodes AddActions target, by default None

serverSCServer, optional

The Server for this Node, by default use the SC default server

Overview:

new

Create a new Node

_get_status_repr

_set_node_attrs

Derive Node group from addaction and target

free

Free the node with /n_free.

run

Turn node on or off with /n_run.

set

Set a control value(s) of the node with n_set.

_update_control

_update_controls

fill

Fill ranges of control values with n_fill.

map

Map a node's control to read from a bus using /n_map or /n_mapa.

release

Set gate as specified.

query

Sends an n_query message to the server.

trace

Trace a node.

move

Move this node

register

Register to be watched.

unregister

Unregister to stop being watched.

on_free

Callback that is executed when this Synth is freed

wait

Wait until this Node is freed

_parse_info

_handle_notification

__eq__

Return self==value.

_get_nodeid

Get the corresponding node id

abstract new(*args, add_action: Optional[Union[AddAction, int]] = None, target: Optional[Union[Node, int]] = None, return_msg: bool = False, **kwargs) Union[Node, sc3nb.osc.osc_communication.OSCMessage][source]

Create a new Node

Parameters:
add_actionAddAction or int, optional

Where the Node should be added, by default AddAction.TO_HEAD (0)

targetNode or int, optional

AddAction target, if None it will be the default group of the server

_get_status_repr() str[source]
_set_node_attrs(target: Optional[Union[Node, int]] = None, add_action: Optional[Union[AddAction, int]] = None) None[source]

Derive Node group from addaction and target

Parameters:
targetint or Node

Target nodeid or Target Node of this Node’s AddAction

add_actionAddAction

AddAction of this Node, default AddAction.TO_HEAD (0)

free(return_msg: bool = False) Union[Node, sc3nb.osc.osc_communication.OSCMessage][source]

Free the node with /n_free.

This will set is_running and is_playing to false. Even when the message is returned to mimic the behavior of the SuperCollider Node See https://doc.sccode.org/Classes/Node.html#-freeMsg

Returns:
Node or OSCMessage

self for chaining or OSCMessage when return_msg=True

run(on: bool = True, return_msg: bool = False) Union[Node, sc3nb.osc.osc_communication.OSCMessage][source]

Turn node on or off with /n_run.

Parameters:
onbool

True for on, False for off, by default True

Returns:
Node or OSCMessage

self for chaining or OSCMessage when return_msg=True

set(argument: Union[str, Dict, List], *values: Any, return_msg: bool = False) Union[Node, sc3nb.osc.osc_communication.OSCMessage][source]

Set a control value(s) of the node with n_set.

Parameters:
argumentstr | dict | list

if string: name of control argument if dict: dict with argument, value pairs if list: use list as message content

valueany, optional

only used if argument is string, by default None

Examples

>>> synth.set("freq", 400)
>>> synth.set({"dur": 1, "freq": 400})
>>> synth.set(["dur", 1, "freq", 400])
_update_control(control: str, value: Any) None[source]
_update_controls(controls: Optional[Dict[str, Any]] = None) None[source]
fill(control: Union[str, int], num_controls: int, value: Any, return_msg: bool = False) Union[Node, sc3nb.osc.osc_communication.OSCMessage][source]

Fill ranges of control values with n_fill.

Parameters:
controlint or string

control index or name

num_controlsint

number of control values to fill

valuefloat or int

value to set

return_msgbool, optional

If True return msg else send it directly, by default False

Returns:
OSCMessage

if return_msg else self

map(control: Union[str, int], bus: sc3nb.sc_objects.bus.Bus, return_msg: bool = False) Union[Node, sc3nb.osc.osc_communication.OSCMessage][source]

Map a node’s control to read from a bus using /n_map or /n_mapa.

Parameters:
controlint or string

control index or name

busBus

control/audio bus

return_msgbool, optional

If True return msg else send it directly, by default False

Returns:
OSCMessage

if return_msg else self

release(release_time: Optional[float] = None, return_msg: bool = False) Union[Node, sc3nb.osc.osc_communication.OSCMessage][source]

Set gate as specified.

https://doc.sccode.org/Classes/Node.html#-release

Parameters:
release_timefloat, optional

amount of time in seconds during which the node will release. If set to a value <= 0, the synth will release immediately. If None using its Envs normal release stage(s)

return_msgbool, optional

If True return msg else send it directly, by default False

Returns:
OSCMessage

if return_msg else self

query() Union[SynthInfo, GroupInfo][source]

Sends an n_query message to the server.

The answer is send to all clients who have registered via the /notify command. Content of answer:

node ID the node’s parent group ID previous node ID, -1 if no previous node. next node ID, -1 if no next node. 1 if the node is a group, 0 if it is a synth

if the node is a group:

ID of the head node, -1 if there is no head node. ID of the tail node, -1 if there is no tail node.

Returns:
SynthInfo or GroupInfo

n_info answer. See above for content description

trace(return_msg: bool = False) Union[Node, sc3nb.osc.osc_communication.OSCMessage][source]

Trace a node.

Print out values of the inputs and outputs for one control period. If node is a group then print the node IDs and names of each node.

Parameters:
return_msgbool, optional

If True return msg else send it directly, by default False

Returns:
Node or OSCMessage

if return_msg else self

move(add_action: AddAction, another_node: Node, return_msg: bool = False) Union[Node, sc3nb.osc.osc_communication.OSCMessage][source]

Move this node

Parameters:
add_actionAddAction [TO_HEAD, TO_TAIL, AFTER, BEFORE]

What add action should be done.

another_nodeNode

The node which is the target of the add action

return_msgbool, optional

If True return msg else send it directly, by default False

Returns:
Node or OSCMessage

if return_msg this will be the OSCMessage, else self

Raises:
ValueError

If a wrong AddAction was provided

abstract register()[source]

Register to be watched.

abstract unregister()[source]

Unregister to stop being watched.

on_free(func)[source]

Callback that is executed when this Synth is freed

wait(timeout: Optional[float] = None) None[source]

Wait until this Node is freed

Raises:
TimeoutError

If timeout was provided and wait timed out.

_parse_info(nodeid: int, group: int, prev_nodeid: int, next_nodeid: int, *rest: Sequence[int]) Union[SynthInfo, GroupInfo][source]
_handle_notification(kind: str, info) None[source]
__eq__(other)[source]

Return self==value.

static _get_nodeid(value: Union[Node, int]) int[source]

Get the corresponding node id

Parameters:
valueNode or int

If a Node is provided it will get its nodeid If a int is provided it will be returned

Returns:
int

nodeid

Raises:
ValueError

When neither Node or int was provided

class sc3nb.Synth(name: Optional[str] = None, controls: Dict[str, Any] = None, *, nodeid: Optional[int] = None, new: bool = True, add_action: Optional[Union[AddAction, int]] = None, target: Optional[Union[Node, int]] = None, server: Optional[sc3nb.sc_objects.server.SCServer] = None)[source]

Bases: Node

Representation of a Synth on SuperCollider.

Create a Python representation of a SuperCollider synth.

Parameters:
namestr, optional

name of the synth to be created, by default “default”

controlsdict, optional

synth control arguments, by default None

nodeidint, optional

ID of the node in SuperCollider, by default sc3nb will create one. Can be set to an existing id to create a Python instance of a running Node.

newbool, optional

True if synth should be created on the server, by default True Should be False if creating an instance of a running Node.

add_actionAddAction or int, optional

Where the Synth should be added, by default AddAction.TO_HEAD (0)

targetNode or int, optional

AddAction target, if None it will be the default group of the server

serverSCServer

sc3nb SCServer instance

Raises:
ValueError

Raised when synth can’t be found via SynthDescLib.global

Examples

>>> scn.Synth(sc, "s1", {"dur": 1, "freq": 400})

Overview:

_update_synth_state

new

Creates the synth on the server with s_new.

get

Get a Synth argument

seti

Set part of an arrayed control.

__getattr__

__setattr__

Implement setattr(self, name, value).

__repr__

Return repr(self).

_update_synth_state(name: Optional[str], controls: Optional[dict])[source]
new(controls: Optional[dict] = None, add_action: Optional[Union[AddAction, int]] = None, target: Optional[Union[Node, int]] = None, *, return_msg: bool = False) Union[Synth, sc3nb.osc.osc_communication.OSCMessage][source]

Creates the synth on the server with s_new.

Attention: Here you create an identical synth! Same nodeID etc. - This will fail if there is already this nodeID on the SuperCollider server!

get(control: str) Any[source]

Get a Synth argument

This will request the value from scsynth with /s_get(n).

Parameters:
controlstr

name of the Synth control argument

abstract seti(*args)[source]

Set part of an arrayed control.

__getattr__(name)[source]
__setattr__(name, value)[source]

Implement setattr(self, name, value).

__repr__() str[source]

Return repr(self).

class sc3nb.Group(*, nodeid: Optional[int] = None, new: bool = True, parallel: bool = False, add_action: AddAction = AddAction.TO_HEAD, target: Optional[Union[Node, int]] = None, server: Optional[sc3nb.sc_objects.server.SCServer] = None)[source]

Bases: Node

Representation of a Group on SuperCollider.

Create a Python representation of a SuperCollider group.

Parameters:
nodeidint, optional

ID of the node in SuperCollider, by default sc3nb will create one. Can be set to an existing id to create a Python instance of a running Node.

newbool, optional

True if synth should be created on the server, by default True Should be False if creating an instance of a running Node.

parallelbool, optional

If True create a parallel group, by default False

add_actionAddAction or int, optional

Where the Group should be added, by default AddAction.TO_HEAD (0)

targetNode or int, optional

AddAction target, if None it will be the default group of the server

serverSCServer, optional

Server instance where this Group is located, by default use the SC default server

Overview:

_update_group_state

new

Creates the synth on the server with g_new / p_new.

move_node_to_head

Move node to this groups head with g_head.

move_node_to_tail

Move node to this groups tail with g_tail.

free_all

Frees all nodes in the group with g_freeAll.

deep_free

Free all synths in this group and its sub-groups with g_deepFree.

dump_tree

Posts a representation of this group's node subtree with g_dumpTree.

query_tree

Send a g_queryTree message for this group.

_repr_pretty_

__repr__

Return repr(self).

_update_group_state(children: Optional[Sequence[Node]] = None) None[source]
new(add_action=AddAction.TO_HEAD, target=None, *, parallel=None, return_msg=False) Union[Group, sc3nb.osc.osc_communication.OSCMessage][source]

Creates the synth on the server with g_new / p_new.

Attention: Here you create an identical group! Same nodeID etc. - This will fail if there is already this nodeID on the SuperCollider server!

Parameters:
add_actionAddAction or int, optional

where the group should be added, by default AddAction.TO_HEAD (0)

targetNode or int, optional

add action target, by default 1

parallelbool, optional

If True use p_new, by default False

return_msgbool, optional

If ture return the OSCMessage instead of sending it, by default False

Returns:
Group

self

move_node_to_head(node, return_msg=False)[source]

Move node to this groups head with g_head.

Parameters:
nodeNode

node to move

return_msgbool, optional

If True return msg else send it directly, by default False

Returns:
Group

self

move_node_to_tail(node, return_msg=False)[source]

Move node to this groups tail with g_tail.

Parameters:
nodeNode

node to move

return_msgbool, optional

If True return msg else send it directly, by default False

Returns:
Group

self

free_all(return_msg=False)[source]

Frees all nodes in the group with g_freeAll.

Parameters:
return_msgbool, optional

If True return msg else send it directly, by default False

Returns:
OSCMessage

if return_msg else self

deep_free(return_msg=False)[source]

Free all synths in this group and its sub-groups with g_deepFree.

Sub-groups are not freed.

Parameters:
return_msgbool, optional

If True return msg else send it directly, by default False

Returns:
OSCMessage

if return_msg else self

dump_tree(post_controls=True, return_msg=False)[source]

Posts a representation of this group’s node subtree with g_dumpTree.

Parameters:
post_controlsbool, optional

True for control values, by default False

return_msgbool, optional

If True return msg else send it directly, by default False

Returns:
OSCMessage

if return_msg else self

query_tree(include_controls=False) Group[source]

Send a g_queryTree message for this group.

See https://doc.sccode.org/Reference/Server-Command-Reference.html#/g_queryTree for details.

Parameters:
include_controlsbool, optional

True for control values, by default False

Returns:
tuple

/g_queryTree.reply

_repr_pretty_(printer, cylce)[source]
__repr__() str[source]

Return repr(self).

class sc3nb.AddAction[source]

Bases: enum.Enum

AddAction of SuperCollider nodes.

This Enum contains the codes for the different ways to add a node.

TO_HEAD = 0
TO_TAIL = 1
BEFORE = 2
AFTER = 3
REPLACE = 4
class sc3nb.SynthDef(name: str, definition: str, sc: Optional[sc3nb.sc.SC] = None)[source]

Wrapper for SuperCollider SynthDef

Create a dynamic synth definition in sc.

Parameters:
namestring

default name of the synthdef creation. The naming convention will be name+int, where int is the amount of already created synths of this definition

definitionstring

Pass the default synthdef definition here. Flexible content should be in double brackets (”…{{flexibleContent}}…”). This flexible content, you can dynamic replace with set_context()

scSC object

SC instance where the synthdef should be created, by default use the default SC instance

synth_descs
synth_defs

Overview:

get_description

Get Synth description

send

Send a SynthDef as bytes.

load

Load SynthDef file at path.

load_dir

Load all SynthDefs from directory.

reset

Reset the current synthdef configuration to the self.definition value.

set_context

Set context in SynthDef.

set_contexts

Set multiple values at onces when you give a dictionary.

unset_remaining

This method will remove all existing placeholders in the current def.

add

This method will add the current_def to SuperCollider.s

free

Free this SynthDef from the server.

__repr__

Return repr(self).

classmethod get_description(name: str, lang: Optional[sc3nb.sclang.SCLang] = None) Optional[Dict[str, sc3nb.sclang.SynthArgument]][source]

Get Synth description

Parameters:
namestr

name of SynthDef

Returns:
Dict

dict with SynthArguments

classmethod send(synthdef_bytes: bytes, server: Optional[sc3nb.sc_objects.server.SCServer] = None)[source]

Send a SynthDef as bytes.

Parameters:
synthdef_bytesbytes

SynthDef bytes

waitbool

If True wait for server reply.

serverSCServer, optional

Server instance that gets the SynthDefs, by default use the SC default server

classmethod load(synthdef_path: str, server: Optional[sc3nb.sc_objects.server.SCServer] = None)[source]

Load SynthDef file at path.

Parameters:
synthdef_pathstr

Path with the SynthDefs

serverSCServer, optional

Server that gets the SynthDefs, by default use the SC default server

classmethod load_dir(synthdef_dir: Optional[str] = None, completion_msg: Optional[bytes] = None, server: Optional[sc3nb.sc_objects.server.SCServer] = None)[source]

Load all SynthDefs from directory.

Parameters:
synthdef_dirstr, optional

directory with SynthDefs, by default sc3nb default SynthDefs

completion_msgbytes, optional

Message to be executed by the server when loaded, by default None

serverSCServer, optional

Server that gets the SynthDefs, by default use the SC default server

reset() SynthDef[source]

Reset the current synthdef configuration to the self.definition value.

After this you can restart your configuration with the same root definition

Returns:
object of type SynthDef

the SynthDef object

set_context(searchpattern: str, value) SynthDef[source]

Set context in SynthDef.

This method will replace a given key (format: “…{{key}}…”) in the synthdef definition with the given value.

Parameters:
searchpatternstring

search pattern in the current_def string

valuestring or something with can parsed to string

Replacement of search pattern

Returns:
selfobject of type SynthDef

the SynthDef object

set_contexts(dictionary: Dict[str, Any]) SynthDef[source]

Set multiple values at onces when you give a dictionary.

Because dictionaries are unsorted, keep in mind, that the order is sometimes ignored in this method.

Parameters:
dictionarydict

{searchpattern: replacement}

Returns:
selfobject of type SynthDef

the SynthDef object

unset_remaining() SynthDef[source]

This method will remove all existing placeholders in the current def.

You can use this at the end of definition to make sure, that your definition is clean. Hint: This method will not remove pyvars

Returns:
selfobject of type SynthDef

the SynthDef object

add(pyvars=None, name: Optional[str] = None, server: Optional[sc3nb.sc_objects.server.SCServer] = None) str[source]

This method will add the current_def to SuperCollider.s

If a synth with the same definition was already in sc, this method will only return the name.

Parameters:
pyvarsdict

SC pyvars dict, to inject python variables

namestr, optional

name which this SynthDef will get

serverSCServer, optional

Server where this SynthDef will be send to, by default use the SC default server

Returns:
str

Name of the SynthDef

free() SynthDef[source]

Free this SynthDef from the server.

Returns:
selfobject of type SynthDef

the SynthDef object

__repr__()[source]

Return repr(self).

class sc3nb.Buffer(bufnum: Optional[int] = None, server: Optional[sc3nb.sc_objects.server.SCServer] = None)[source]

A Buffer object represents a SuperCollider3 Buffer on scsynth and provides access to low-level buffer commands of scsynth via methods of the Buffer objects.

The constructor merely initializes a buffer:

  • it selects a buffer number using the server’s buffer allocator

  • it initializes attribute variables

Parameters:
bufnumint, optional

buffer number to be used on scsynth. Defaults to None, can be set to enforce a given bufnum

serverSCServer, optional

The server instance to establish the Buffer, by default use the SC default server

Notes

For more information on Buffer commands, refer to the Server Command Reference in SC3. https://doc.sccode.org/Reference/Server-Command-Reference.html#Buffer%20Commands

Examples

(see examples/buffer-examples.ipynb)

>>> b = Buffer().read(...)
>>> b = Buffer().load_data(...)
>>> b = Buffer().alloc(...)
>>> b = Buffer().load_asig(...)
>>> b = Buffer().use_existing(...)
>>> b = Buffer().copy(Buffer)
Attributes:
serverthe SCServer object

to communicate with scsynth

_bufnumint

buffer number = bufnum id on scsynth

_srint

the sampling rate of the buffer

_channelsint

number of channels of the buffer

_samplesint

buffer length = number of sample frames

_alloc_modestr

[‘file’, ‘alloc’, ‘data’, ‘existing’, ‘copy’] according to previously used generator, defaults to None

_allocatedboolean

True if Buffer has been allocated by any of the initialization methods

_pathstr

path to the audio file used in load_file()

Overview:

read

Allocate buffer memory and read a sound file.

alloc

Allocate buffer memory.

load_data

Allocate buffer memory and read input data.

load_collection

Wrapper method of Buffer.load_data()

load_asig

Create buffer from asig

use_existing

Creates a buffer object from already existing Buffer bufnum.

copy_existing

Duplicate an existing buffer

fill

Fill range of samples with value(s).

gen

Call a command to fill a buffer.

zero

Set buffer data to zero.

gen_sine1

Fill the buffer with sine waves & given amplitude

gen_sine2

Fill the buffer with sine waves

gen_sine3

Fill the buffer with sine waves & given a list of

gen_cheby

Fills a buffer with a series of chebyshev polynomials, which can be

gen_copy

Copy samples from the source buffer to the destination buffer

play

Play the Buffer using a Synth

write

Write buffer data to a sound file

close

Close soundfile after using a Buffer with DiskOut

to_array

Return the buffer data as an array representation.

query

Get buffer info.

__repr__

Return repr(self).

free

Free buffer data.

_gen_flags

Generate Wave Fill Commands flags from booleans

read(path: str, starting_frame: int = 0, num_frames: int = -1, channels: Optional[Union[int, Sequence[int]]] = None) Buffer[source]

Allocate buffer memory and read a sound file.

If the number of frames argument num_frames is negative or zero, the entire file is read.

Parameters:
pathstring

path name of a sound file.

starting_frameint

starting frame in file

num_framesint

number of frames to read

channelslist | int

channels and order of channels to be read from file. if only a int is provided it is loaded as only channel

Returns:
selfBuffer

the created Buffer object

Raises:
RuntimeError

If the Buffer is already allocated.

alloc(size: int, sr: int = 44100, channels: int = 1) Buffer[source]

Allocate buffer memory.

Parameters:
sizeint

number of frames

srint

sampling rate in Hz (optional. default = 44100)

channelsint

number of channels (optional. default = 1 channel)

Returns:
selfBuffer

the created Buffer object

Raises:
RuntimeError

If the Buffer is already allocated.

load_data(data: numpy.ndarray, sr: int = 44100, mode: str = 'file', sync: bool = True) Buffer[source]

Allocate buffer memory and read input data.

Parameters:
datanumpy array

Data which should inserted

srint, default: 44100

sample rate

mode‘file’ or ‘osc’

Insert data via filemode (‘file’) or n_set OSC commands (‘osc’) Bundling is only supported for ‘osc’ mode and if sync is False.

sync: bool, default: True

Use SCServer.sync after sending messages when mode = ‘osc’

Returns:
selfBuffer

the created Buffer object

Raises:
RuntimeError

If the Buffer is already allocated.

load_collection(data: numpy.ndarray, mode: str = 'file', sr: int = 44100) Buffer[source]

Wrapper method of Buffer.load_data()

load_asig(asig: pya.Asig, mode: str = 'file') Buffer[source]

Create buffer from asig

Parameters:
asigpya.Asig

asig to be loaded in buffer

modestr, optional

Insert data via filemode (‘file’) or n_set OSC commands (‘osc’), by default ‘file’

Returns:
selfBuffer

the created Buffer object

Raises:
RuntimeError

If the Buffer is already allocated.

use_existing(bufnum: int, sr: int = 44100) Buffer[source]

Creates a buffer object from already existing Buffer bufnum.

Parameters:
bufnumint

buffer node id

srint

Sample rate

Returns:
selfBuffer

the created Buffer object

Raises:
RuntimeError

If the Buffer is already allocated.

copy_existing(buffer: Buffer) Buffer[source]

Duplicate an existing buffer

Parameters:
bufferBuffer object

Buffer which should be duplicated

Returns:
selfBuffer

the newly created Buffer object

Raises:
RuntimeError

If the Buffer is already allocated.

fill(start: int = 0, count: int = 0, value: float = 0) Buffer[source]

Fill range of samples with value(s).

Parameters:
startint or list

int : sample starting index list : n*[start, count, value] list

countint

number of samples to fill

valuefloat

value

Returns:
selfBuffer

the created Buffer object

Raises:
RuntimeError

If the Buffer is not allocated yet.

gen(command: str, args: List[Any]) Buffer[source]

Call a command to fill a buffer. If you know, what you do -> you can use this method.

Parameters:
commandstr

What fill command to use.

argsList[Any]

Arguments for command

Returns:
selfBuffer

the created Buffer object

Raises:
RuntimeError

If the Buffer is not allocated yet.

zero() Buffer[source]

Set buffer data to zero.

Returns:
selfBuffer

the created Buffer object

Raises:
RuntimeError

If the Buffer is not allocated yet.

gen_sine1(amplitudes: List[float], normalize: bool = False, wavetable: bool = False, clear: bool = False) Buffer[source]

Fill the buffer with sine waves & given amplitude

Parameters:
amplitudeslist

The first float value specifies the amplitude of the first partial, the second float value specifies the amplitude of the second partial, and so on.

normalizebool

Normalize peak amplitude of wave to 1.0.

wavetablebool

If set, then the buffer is written in wavetable format so that it can be read by interpolating oscillators.

clearbool

If set then the buffer is cleared before new partials are written into it. Otherwise the new partials are summed with the existing contents of the buffer

Returns:
selfBuffer

the created Buffer object

Raises:
RuntimeError

If the Buffer is not allocated yet.

gen_sine2(freq_amps: List[float], normalize: bool = False, wavetable: bool = False, clear: bool = False) Buffer[source]

Fill the buffer with sine waves given list of [frequency, amplitude] lists

Parameters:
freq_ampslist

Similar to sine1 except that each partial frequency is specified explicitly instead of being an integer multiple of the fundamental. Non-integer partial frequencies are possible.

normalizebool

If set, normalize peak amplitude of wave to 1.0.

wavetablebool

If set, the buffer is written in wavetable format so that it can be read by interpolating oscillators.

clearbool

If set, the buffer is cleared before new partials are written into it. Otherwise the new partials are summed with the existing contents of the buffer.

Returns:
selfBuffer

the created Buffer object

Raises:
RuntimeError

If the Buffer is not allocated yet.

gen_sine3(freqs_amps_phases: List[float], normalize: bool = False, wavetable: bool = False, clear: bool = False) Buffer[source]

Fill the buffer with sine waves & given a list of [frequency, amplitude, phase] entries.

Parameters:
freqs_amps_phaseslist

Similar to sine2 except that each partial may have a nonzero starting phase.

normalizebool

if set, normalize peak amplitude of wave to 1.0.

wavetablebool

If set, the buffer is written in wavetable format so that it can be read by interpolating oscillators.

clearbool

If set, the buffer is cleared before new partials are written into it. Otherwise the new partials are summed with the existing contents of the buffer.

Returns:
selfBuffer

the created Buffer object

Raises:
RuntimeError

If the Buffer is not allocated yet.

gen_cheby(amplitudes: List[float], normalize: bool = False, wavetable: bool = False, clear: bool = False) Buffer[source]

Fills a buffer with a series of chebyshev polynomials, which can be defined as cheby(n) = amplitude * cos(n * acos(x))

Parameters:
amplitudeslist

The first float value specifies the amplitude for n = 1, the second float value specifies the amplitude for n = 2, and so on

normalizebool

If set, normalize the peak amplitude of the Buffer to 1.0.

wavetablebool

If set, the buffer is written in wavetable format so that it can be read by interpolating oscillators.

clearbool

If set the buffer is cleared before new partials are written into it. Otherwise the new partials are summed with the existing contents of the buffer.

Returns:
selfBuffer

the created Buffer object

Raises:
RuntimeError

If the Buffer is not allocated yet.

gen_copy(source: Buffer, source_pos: int, dest_pos: int, copy_amount: int) Buffer[source]

Copy samples from the source buffer to the destination buffer specified in the b_gen command.

Parameters:
sourceBuffer

Source buffer object

source_posint

sample position in source

dest_posint

sample position in destination

copy_amountint

number of samples to copy. If the number of samples to copy is negative, the maximum number of samples possible is copied.

Returns:
selfBuffer

the created Buffer object

Raises:
RuntimeError

If the Buffer is not allocated yet.

play(rate: float = 1, loop: bool = False, pan: float = 0, amp: float = 0.3) sc3nb.sc_objects.node.Synth[source]

Play the Buffer using a Synth

Parameters:
ratefloat, optional

plackback rate, by default 1

loopbool, optional

if True loop the playback, by default False

panint, optional

pan position, -1 is left, +1 is right, by default 0

ampfloat, optional

amplitude, by default 0.3

Returns:
Synth

Synth to control playback.

Raises:
RuntimeError

If the Buffer is not allocated yet.

write(path: str, header: str = 'wav', sample: str = 'float', num_frames: int = -1, starting_frame: int = 0, leave_open: bool = False) Buffer[source]

Write buffer data to a sound file

Parameters:
pathstring

path name of a sound file.

headerstring

header format. Header format is one of: “aiff”, “next”, “wav”, “ircam””, “raw”

samplestring

sample format. Sample format is one of: “int8”, “int16”, “int24”, “int32”, “float”, “double”, “mulaw”, “alaw”

num_framesint

number of frames to write. -1 means all frames.

starting_frameint

starting frame in buffer

leave_openboolean

Whether you want the buffer file left open. For use with DiskOut you will want this to be true. The file is created, but no frames are written until the DiskOut UGen does so. The default is false which is the correct value for all other cases.

Returns:
selfBuffer

the Buffer object

Raises:
RuntimeError

If the Buffer is not allocated yet.

close() Buffer[source]

Close soundfile after using a Buffer with DiskOut

Returns:
selfBuffer

the Buffer object

Raises:
RuntimeError

If the Buffer is not allocated yet.

to_array() numpy.ndarray[source]

Return the buffer data as an array representation.

Returns:
np.ndarray:

Values of the buffer

Raises:
RuntimeError

If the Buffer is not allocated yet.

query() BufferInfo[source]

Get buffer info.

Returns:
Tuple:

(buffer number, number of frames, number of channels, sampling rate)

Raises:
RuntimeError

If the Buffer is not allocated yet.

__repr__() str[source]

Return repr(self).

free() None[source]

Free buffer data.

Raises:
RuntimeError

If the Buffer is not allocated yet.

_gen_flags(a_normalize=False, a_wavetable=False, a_clear=False) int[source]

Generate Wave Fill Commands flags from booleans according to the SuperCollider Server Command Reference.

Parameters:
a_normalizebool, optional

Normalize peak amplitude of wave to 1.0, by default False

a_wavetablebool, optional

If set, then the buffer is written in wavetable format so that it can be read by interpolating oscillators, by default False

a_clearbool, optional

If set then the buffer is cleared before new partials are written into it. Otherwise the new partials are summed with the existing contents of the buffer, by default False

Returns:
int

Wave Fill Commands flags

class sc3nb.Bus(rate: Union[BusRate, str], num_channels: int = 1, index: Optional[int] = None, server: Optional[sc3nb.sc_objects.server.SCServer] = None)[source]

Represenation of Control or Audio Bus(es) on the SuperCollider Server

If num_channels > 1 this will be represent muliple Buses in a row.

Parameters:
rateUnion[BusRate, str]

Rate of the Bus, either control or audio

num_channelsint, optional

How many channels to allocate, by default 1

indexint, optional

Starting Bus index this Bus, by default this will be handled by the servers Bus allocator.

serverSCServer, optional

Server instance for this Bus, by default the default SC server instance.

Overview:

is_audio_bus

Rate check

is_control_bus

Rate check

set

Set ranges of bus values.

fill

Fill bus(es) to one value.

get

Get bus value(s).

free

Mark this Buses ids as free again

__del__

__repr__

Return repr(self).

is_audio_bus() bool[source]

Rate check

Returns:
bool

True if this is a audio bus

is_control_bus() bool[source]

Rate check

Returns:
bool

True if this is a control bus

set(*values: Sequence[Union[int, float]], return_msg=False) Union[Bus, sc3nb.osc.osc_communication.OSCMessage][source]

Set ranges of bus values.

Parameters:
valuessequence of int or float

Values that should be set

return_msgbool, optional

If True return msg else send it directly, by default False

Raises:
RuntimeError

If trying to setn an Audio Bus

fill(value: Union[int, float], return_msg=False) Union[Bus, sc3nb.osc.osc_communication.OSCMessage][source]

Fill bus(es) to one value.

Parameters:
valueUnion[int, float]

value for the buses

return_msgbool, optional

If True return msg else send it directly, by default False

Raises:
RuntimeError

If fill is used on a Audio Bus

get() Union[Union[int, float], Sequence[Union[int, float]]][source]

Get bus value(s).

Returns:
bus value or sequence of bus values

The current value of this bus Multiple values if this bus has num_channels > 1

Raises:
RuntimeError

If get is used on an Audio Bus

free(clear: bool = True) None[source]

Mark this Buses ids as free again

Parameters:
clearbool, optional

Reset bus value(s) to 0, by default True

__del__() None[source]
__repr__() str[source]

Return repr(self).

class sc3nb.Score[source]

Overview:

load_file

Load a OSC file into a dict.

write_file

Write this score as binary OSC file for NRT synthesis.

record_nrt

Write an OSC file from the messages and wri

classmethod load_file(path: Union[str, bytes, os.PathLike]) Dict[float, List[sc3nb.osc.osc_communication.OSCMessage]][source]

Load a OSC file into a dict.

Parameters:
pathUnion[str, bytes, os.PathLike]

Path of the OSC file.

Returns:
Dict[float, List[OSCMessage]]

dict with time tag as keys and lists of OSCMessages as values.

classmethod write_file(messages: Dict[float, List[sc3nb.osc.osc_communication.OSCMessage]], path: Union[str, bytes, os.PathLike], tempo: float = 1)[source]

Write this score as binary OSC file for NRT synthesis.

Parameters:
messagesDict[float, List[OSCMessage]]

Dict with times as key and lists of OSC messages as values

pathUnion[str, bytes, os.PathLike]

output path for the binary OSC file

tempofloat

Times will be multiplied by 1/tempo

classmethod record_nrt(messages: Dict[float, List[sc3nb.osc.osc_communication.OSCMessage]], osc_path: str, out_file: str, in_file: Optional[str] = None, sample_rate: int = 44100, header_format: str = 'AIFF', sample_format: str = 'int16', options: Optional[sc3nb.sc_objects.server.ServerOptions] = None)[source]

Write an OSC file from the messages and wri

Parameters:
messagesDict[float, List[OSCMessage]]

Dict with times as key and lists of OSC messages as values.

osc_pathstr

Path of the binary OSC file.

out_filestr

Path of the resulting sound file.

in_fileOptional[str], optional

Path of input soundfile, by default None.

sample_rateint, optional

sample rate for synthesis, by default 44100.

header_formatstr, optional

header format of the output file, by default “AIFF”.

sample_formatstr, optional

sample format of the output file, by default “int16”.

optionsOptional[ServerOptions], optional

instance of server options to specify server options, by default None

Returns:
subprocess.CompletedProcess

Completed scsynth non-realtime process.

class sc3nb.Recorder(path: str = 'record.wav', nr_channels: int = 2, rec_header: str = 'wav', rec_format: str = 'int16', bufsize: int = 65536, server: Optional[sc3nb.sc_objects.server.SCServer] = None)[source]

Allows to record audio easily.

Create and prepare a recorder.

Parameters:
pathstr, optional

path of recording file, by default “record.wav”

nr_channelsint, optional

Number of channels, by default 2

rec_headerstr, optional

File format, by default “wav”

rec_formatstr, optional

Recording resolution, by default “int16”

bufsizeint, optional

size of buffer, by default 65536

serverSCServer, optional

server used for recording, by default use the SC default server

Overview:

prepare

Pepare the recorder.

start

Start the recording.

pause

Pause the recording.

resume

Resume the recording

stop

Stop the recording.

__repr__

Return repr(self).

__del__

prepare(path: str = 'record.wav', nr_channels: int = 2, rec_header: str = 'wav', rec_format: str = 'int16', bufsize: int = 65536)[source]

Pepare the recorder.

Parameters:
pathstr, optional

path of recording file, by default “record.wav”

nr_channelsint, optional

Number of channels, by default 2

rec_headerstr, optional

File format, by default “wav”

rec_formatstr, optional

Recording resolution, by default “int16”

bufsizeint, optional

size of buffer, by default 65536

Raises:
RuntimeError

When Recorder does not needs to be prepared.

start(timetag: float = 0, duration: Optional[float] = None, node: Union[sc3nb.sc_objects.node.Node, int] = 0, bus: int = 0)[source]

Start the recording.

Parameters:
timetagfloat, by default 0 (immediately)

Time (or time offset when <1e6) to start

durationfloat, optional

Length of the recording, by default until stopped.

nodeUnion[Node, int], optional

Node that should be recorded, by default 0

busint, by default 0

Bus that should be recorded

Raises:
RuntimeError

When trying to start a recording unprepared.

pause(timetag: float = 0)[source]

Pause the recording.

Parameters:
timetagfloat, by default 0 (immediately)

Time (or time offset when <1e6) to pause

Raises:
RuntimeError

When trying to pause if not recording.

resume(timetag: float = 0)[source]

Resume the recording

Parameters:
timetagfloat, by default 0 (immediately)

Time (or time offset when <1e6) to resume

Raises:
RuntimeError

When trying to resume if not paused.

stop(timetag: float = 0)[source]

Stop the recording.

Parameters:
timetagfloat, by default 0 (immediately)

Time (or time offset when <1e6) to stop

Raises:
RuntimeError

When trying to stop if not started.

__repr__() str[source]

Return repr(self).

__del__()[source]
class sc3nb.TimedQueue(relative_time: bool = False, thread_sleep_time: float = 0.001, drop_time_threshold: float = 0.5)[source]

Accumulates events as timestamps and functions.

Executes given functions according to the timestamps

Parameters:
relative_timebool, optional

If True, use relative time, by default False

thread_sleep_timefloat, optional

Sleep time in seconds for worker thread, by default 0.001

drop_time_thresholdfloat, optional

Threshold for execution time of events in seconds. If this is exceeded the event will be dropped, by default 0.5

Overview:

close

Closes event processing without waiting for pending events

join

Closes event processing after waiting for pending events

complete

Blocks until all pending events have completed

put

Adds event to queue

get

Get latest event from queue and remove event

peek

Look up latest event from queue

empty

Checks if queue is empty

pop

Removes latest event from queue

__worker

Worker function to process events

__repr__

Return repr(self).

elapse

Add time delta to the current queue time.

close() None[source]

Closes event processing without waiting for pending events

join() None[source]

Closes event processing after waiting for pending events

complete() None[source]

Blocks until all pending events have completed

put(timestamp: float, function: Callable[Ellipsis, None], args: Iterable[Any] = (), spawn: bool = False) None[source]

Adds event to queue

Parameters:
timestampfloat

Time (POSIX) when event should be executed

functionCallable[…, None]

Function to be executed

argsIterable[Any], optional

Arguments to be passed to function, by default ()

spawnbool, optional

if True, create new sub-thread for function, by default False

Raises:
TypeError

raised if function is not callable

get() Event[source]

Get latest event from queue and remove event

Returns:
Event

Latest event

peek() Event[source]

Look up latest event from queue

Returns:
Event

Latest event

empty() bool[source]

Checks if queue is empty

Returns:
bool

True if queue if empty

pop() None[source]

Removes latest event from queue

__worker(sleep_time: float, close_event: threading.Event) NoReturn[source]

Worker function to process events

__repr__()[source]

Return repr(self).

elapse(time_delta: float) None[source]

Add time delta to the current queue time.

Parameters:
time_deltafloat

Additional time

class sc3nb.TimedQueueSC(server: sc3nb.osc.osc_communication.OSCCommunication = None, relative_time: bool = False, thread_sleep_time: float = 0.001)[source]

Bases: TimedQueue

Timed queue with OSC communication.

Parameters:
serverOSCCommunication, optional

OSC server to handle the bundlers and messsages, by default None

relative_timebool, optional

If True, use relative time, by default False

thread_sleep_timefloat, optional

Sleep time in seconds for worker thread, by default 0.001

Overview:

put_bundler

Add a Bundler to queue

put_msg

Add a message to queue

put_bundler(onset: float, bundler: sc3nb.osc.osc_communication.Bundler) None[source]

Add a Bundler to queue

Parameters:
onsetfloat

Sending timetag of the Bundler

bundlerBundler

Bundler that will be sent

put_msg(onset: float, msg: Union[sc3nb.osc.osc_communication.OSCMessage, str], msg_params: Iterable[Any]) None[source]

Add a message to queue

Parameters:
onsetfloat

Sending timetag of the message

msgUnion[OSCMessage, str]

OSCMessage or OSC address

msg_paramsIterable[Any]

If msg is str, this will be the parameters of the created OSCMessage

class sc3nb.OSCMessage(msg_address: str, msg_parameters: Optional[Union[Sequence, Any]] = None)[source]

Class for creating messages to send over OSC

Parameters:
msg_addressstr

OSC message address

msg_parametersOptional[Union[Sequence]], optional

OSC message parameters, by default None

Overview:

to_pythonosc

Return python-osc OscMessage

_build_message

Builds pythonsosc OSC message.

__repr__

Return repr(self).

to_pythonosc() pythonosc.osc_message.OscMessage[source]

Return python-osc OscMessage

static _build_message(msg_address: str, msg_parameters: Optional[Union[Sequence, Any]] = None) pythonosc.osc_message.OscMessage[source]

Builds pythonsosc OSC message.

Parameters:
msg_addressstr

SuperCollider address.

msg_parameterslist, optional

List of parameters to add to message.

Returns:
OscMessage

Message ready to be sent.

__repr__() str[source]

Return repr(self).

class sc3nb.Bundler(timetag: float = 0, msg: Optional[Union[OSCMessage, str]] = None, msg_params: Optional[Sequence[Any]] = None, *, server: Optional[OSCCommunication] = None, receiver: Optional[Union[str, Tuple[str, int]]] = None, send_on_exit: bool = True)[source]

Class for creating OSCBundles and bundling of messages

Create a Bundler

Parameters:
timetagfloat, optional

Starting time at which bundle content should be executed. If timetag > 1e6 it is interpreted as POSIX time. If timetag <= 1e6 it is assumed to be relative value in seconds and is added to time.time(), by default 0, i.e. ‘now’.

msgOSCMessage or str, optional

OSCMessage or message address, by default None

msg_paramssequence of any type, optional

Parameters for the message, by default None

serverOSCCommunication, optional

OSC server, by default None

receiverUnion[str, Tuple[str, int]], optional

Where to send the bundle, by default send to default receiver of server

send_on_exitbool, optional

Whether the bundle is sent when using as context manager, by default True

Overview:

wait

Add time to internal time

add

Add content to this Bundler.

messages

Generate a dict with all messages in this Bundler.

send

Send this Bundler.

to_raw_osc

Create a raw OSC Bundle from this bundler.

to_pythonosc

Build this bundle.

_calc_timetag

__deepcopy__

__enter__

__exit__

__repr__

Return repr(self).

wait(time_passed: float) None[source]

Add time to internal time

Parameters:
time_passedfloat

How much seconds should be passed.

add(*args) Bundler[source]

Add content to this Bundler.

Parameters:
argsaccepts an OSCMessage or Bundler

or a timetag with an OSCMessage or Bundler or Bundler arguments like

(timetag, msg_addr, msg_params) (timetag, msg_addr) (timetag, msg)

Returns:
Bundler

self for chaining

messages(start_time: Optional[float] = 0.0, delay: Optional[float] = None) Dict[float, List[OSCMessage]][source]

Generate a dict with all messages in this Bundler.

They dict key is the time tag of the messages.

Parameters:
start_timeOptional[float], optional

start time when using relative timing, by default 0.0

Returns:
Dict[float, List[OSCMessage]]

dict containg all OSCMessages

send(server: Optional[OSCCommunication] = None, receiver: Tuple[str, int] = None, bundle: bool = True)[source]

Send this Bundler.

Parameters:
serverOSCCommunication, optional

Server instance for sending the bundle. If None it will use the server from init or try to use sc3nb.SC.get_default().server, by default None

receiverTuple[str, int], optional

Address (ip, port) to send to, if None it will send the bundle to the default receiver of the Bundler

bundlebool, optional

If True this is allowed to be bundled, by default True

Raises:
RuntimeError

When no server could be found.

to_raw_osc(start_time: Optional[float] = None, delay: Optional[float] = None) bytes[source]

Create a raw OSC Bundle from this bundler.

Parameters:
start_timeOptional[float], optional

used as start time when using relative timing, by default time.time()

delay: float, optinal

used to delay the timing.

Returns:
OscBundle

bundle instance for sending

to_pythonosc(start_time: Optional[float] = None, delay: Optional[float] = None) pythonosc.osc_bundle.OscBundle[source]

Build this bundle.

Parameters:
start_timeOptional[float], optional

used as start time when using relative timing, by default time.time()

delay: float, optinal

used to delay the timing.

Returns:
OscBundle

bundle instance for sending

_calc_timetag(start_time: Optional[float])[source]
__deepcopy__(memo) Bundler[source]
__enter__()[source]
__exit__(exc_type, exc_value, exc_traceback)[source]
__repr__() str[source]

Return repr(self).

Subpackages

Submodules