Csound API, version 7

Contents

Csound API, version 7#

This API is valid for versions of csound >= 7.0. The correct API is imported automatically based in the version of csound installed in the system and both APIs (for csound 6 and csound 7) are for the most part compatible. With time it is expected that csound 7 will slowly drift away.

Note

At the moment there is no official release of csound 7, so this API is kept in sync with the develop branch of csound and is tested against it.

In general it can be said that the API has been reduced for csound 7. Some methods which existed to set specific options, for example, have been discontinued, but the same functionality is still available through command-line options.

Csound([hostData, opcodeDir, pointer])

This class represents an instance of a csound process

PerformanceThread(csound)

Runs Csound in a separate thread.


class libcsound.api7.Csound(hostData=None, opcodeDir='', pointer=None)[source]#

This class represents an instance of a csound process

Parameters:
  • hostData – any data, will be accessible within certain callbacks

  • opcodeDir – the folder where to load opcodes from. If not given, default folders are used

  • pointer (c_void_p | None) – if given, the result of calling libcsound.csoundCreate(…), uses the given csound process instead of creating a new one

cs#

a pointer to a csound process

Methods:

A4()

Returns the A4 frequency reference.

APIVersion()

For compatibility, csound 7 does not implement an api version at the moment

UDPServerStart(port)

Starts the UDP server on a supplied port number.

allocatedChannels()

Returns a list of allocated channels

appendOpcode(opname, dsblksiz, flags, ...[, ...])

Appends an opcode implemented by external software.

arrayData(adat)

Get the data from the ARRAYDAT adat.

arrayDataDimensions(adat)

Get the dimensions of the ARRAYDAT adat.

arrayDataSizes(adat)

Get the sizes of each dimension of the ARRAYDAT adat.

arrayDataType(adat)

Get the type of data the ARRAYDAT adat.

audioChannel(name[, samples])

Copies the audio channel identified by name into ndarray samples.

audioDevList(isOutput)

List of available input and output audio devices.

channelDatasize(name)

Returns the size of data stored in a channel.

channelInfo(name)

Query info about a channel

channelPtr(name, kind[, mode])

Returns a pointer to the specified channel and an error message.

channelVarTypeName(name)

Returns the var type for a channel name.

cleanup()

This is not needed in csound7, only here for compatibility

compileCommandLine(*args)

Compiles csound command line arguments

compileCsd(path[, block])

Compiles a Csound input file (.csd file)

compileCsdText(code[, block])

Compiles a Csound input file (.csd file) or a text string.

compileOrc(orc[, block])

Parses and compiles the given orchestra from a string.

compileOrcAsync(orc)

Async version of compileOrc().

compileOrcHeader([sr, nchnls, nchnls_i, ...])

Compile the orchestra header (sr, ksmps, nchnls, ...)

controlChannel(name)

Retrieves the value of control channel identified by name.

controlChannelHints(name)

Returns special parameters (if any) of a control channel.

createCircularBuffer(numelem[, elemsize])

Creates a circular buffer with numelem number of elements.

createMessageBuffer([echo])

Creates a buffer for storing messages printed by Csound.

csound()

Returns the opaque pointer to the underlying CSOUND struct.

currentTimeSamples()

Current performance time in samples.

debug()

Returns whether Csound is set to print debug messages.

deleteChannelList(lst)

Releases a channel list previously returned by list_channels().

destroyCircularBuffer(buffer)

Frees circular buffer.

destroyMessageBuffer()

Releases all memory used by the message buffer.

env(name)

Gets the value of environment variable name.

evalCode(code)

Evaluate the given code (blocking), returns the value passed to the return opcode

event(kind, pfields[, block])

Send a new event.

eventString(message[, block])

Schedule a new event as a string.

firstMessage()

Returns the first message from the buffer.

firstMessageAttr()

Returns the attribute parameter of the first message in the buffer.

flushCircularBuffer(buffer)

Empties circular buffer of any remaining data.

get0dBFS()

Returns the 0dBFS level of the spin/spout buffers.

hostData()

Returns host data.

initArrayChannel(name, dtype, size)

Create and initialise an array channel with a given array type.

initPvsChannel(name, fftsize, overlap, ...)

Create/initialise an Fsig channel.

inputMessage(message)

Send a new event as a string, blocking

inputMessageAsync(message)

Send a new event as a string, async

instrNumber(name)

Get the instrument number for a given instrument name string.

isScorePending()

Tells whether Csound score events are performed or not.

iterMessages()

Iterate over the messages in the message buffer

keyPress(c)

Sets the ASCII code of the most recent key pressed.

killInstance(instr, mode[, allowRelease])

Kills off one or more running instances of an instrument.

kr()

Number of control samples per second.

ksmps()

Number of audio sample frames per control sample.

listChannels()

Returns a list of allocated channels and an error message.

loadPlugins(directory)

Loads all plugins from a given directory.

lockChannel(channel)

Locks access to the channel.

message(message)

Displays an informational message.

messageCnt()

Returns the number of pending messages in the buffer.

messageLevel()

Returns the Csound message level (from 0 to 231).

messageS(attr, message)

Prints message with special attributes.

midiDevList([isOutput])

Returns a list of available input or output midi devices.

module(number)

Retrieves a module name and type given a number.

modules()

Returns a list of modules

nchnls()

Number of output channels

nchnlsInput()

Number of input channels

params([params])

Current set of parameters from a CSOUND instance.

peekCircularBuffer(buffer, out, numitems)

Reads from circular buffer without removing them from the buffer.

perform()

Handles input events and performs audio output.

performKsmps()

Handles input events, and performs audio output for one cycle

performanceThread()

Creates a performance thread attached to this csound instance

popFirstMessage()

Removes the first message from the buffer.

pvsData(pvsdat)

Get the analysis data frame from the PVSDAT pvsdat.

pvsDataFftSize(pvsdat)

Get the analysis FFT size used by the PVSDAT pvsdat.

pvsDataFormat(pvsdat)

Get the analysis data format used by the PVSDAT pvsdat.

pvsDataFramecount(pvsdat)

Get the current framecount from PVSDAT pvsdat.

pvsDataOverlap(pvsdat)

Get the analysis overlap size used by the PVSDAT pvsdat.

pvsDataWindowSize(pvsdat)

Get the analysis window size used by the PVSDAT pvsdat.

readCircularBuffer(buffer, out, numitems)

Reads from circular buffer.

readMessage()

Reads a message from the message buffer and removes it from it

registerKeyboardCallback(function, userdata, ...)

Registers general purpose callback functions for keyboard events.

removeKeyboardCallback(function)

Removes a callback previously set with register_keyboard_callback().

reset()

Resets all internal memory and state.

rewindScore()

Rewinds a compiled Csound score.

runUtility(name, args)

Runs utility with the specified name and command line arguments.

scoreEvent(kind, pfields)

Send a new event

scoreEventAsync(kind, pfields)

Send a new event, async

scoreOffsetSeconds()

Returns the score time beginning.

scoreTime()

Returns the current score time.

setArrayData(adat, data)

Set the data in the ARRAYDAT adat.

setAudioChannel(name, samples)

Sets the audio channel name with data from the ndarray samples.

setControlChannel(name, val)

Sets the value of control channel identified by name.

setControlChannelHints(name[, hints, behav, ...])

setDebug(debug)

Sets whether Csound prints debug messages.

setDrawGraphCallback(function)

Called by external software to set Csound's DrawGraph function.

setEndMarker(time)

Add an end event ('e') to the score

setExitGraphCallback(function)

Called by external software to set Csound's ExitGraph function.

setExternalMidiErrorStringCallback(function)

Sets a callback for converting MIDI error codes to strings.

setExternalMidiInCloseCallback(function)

Sets a callback for closing real time MIDI input.

setExternalMidiInOpenCallback(function)

Sets a callback for opening real-time MIDI input.

setExternalMidiOutCloseCallback(function)

Sets a callback for closing real time MIDI input.

setExternalMidiOutOpenCallback(function)

Sets a callback for opening real-time MIDI input.

setExternalMidiReadCallback(function)

Sets a callback for reading from real time MIDI input.

setExternalMidiWriteCallback(function)

Sets a callback for reading from real time MIDI input.

setGlobalEnv(name, value)

Set the global value of environment variable name to value.

setHostAudioIO()

Disable all default handling of sound I/O.

setHostData(data)

Sets host data.

setHostImplementedMidiIO(state)

Called with state=True disables native midi IO

setHostMidiIO()

Disable all default handling of MIDI I/O.

setInput(name)

Sets input source.

setInputChannelCallback(function)

Sets the function to call whenever the invalue opcode is used.

setIsGraphable(isGraphable)

Tells Csound whether external graphic table display is supported.

setKillGraphCallback(function)

Called by external software to set Csound's KillGraph function.

setMakeGraphCallback(function)

Called by external software to set Csound's MakeGraph function.

setMessageLevel(messageLevel)

Sets the Csound message level (from 0 to 231).

setMessageStringCallback(attr, function)

Sets an alternative message print function.

setMidiDeviceListCallback(function)

Sets a callback for obtaining a list of MIDI devices.

setMidiInput(name)

Sets MIDI input device name/number.

setMidiModule(module)

Sets the current MIDI IO module.

setOpenFileCallback(function)

Sets a callback for opening a file.

setOpenSoundFileCallback(function)

Sets a callback for opening a sound file.

setOption(option)

Set csound option/options

setOutput(name[, filetype, format])

Sets output destination, filetype and format.

setOutputChannelCallback(function)

Sets the function to call whenever the outvalue opcode is used.

setPvsData(pvsdat, frame)

Set the analysis data frame in the PVSDAT pvsdat.

setRTAudioModule(module)

Sets the current RT audio module.

setScoreOffsetSeconds(time)

Csound score events prior to the specified time are not performed.

setScorePending(pending)

Sets whether Csound score events are performed or not.

setStringChannel(name, string)

Sets the string channel identified by name with string.

setStringData(sdata, string)

Set a STRINGDAT structure with a null-terminated string.

sizeOfMYFLT()

Size of MYFLT in bytes.

sleep(milliseconds)

Waits for at least the specified number of milliseconds.

spin()

Returns the Csound audio input working buffer (spin) as an ndarray.

spout()

Returns the audio output working buffer (spout) as a numpy array

sr()

Returns the number of audio sample frames per second.

start()

Prepares Csound for performance.

stop()

Only here for compatibility, not exposed in csound7

stringChannel(name)

Return a string from the string channel identified by name.

stringData(sdata)

Get a null-terminated string from a STRINGDAT structure.

systemSr([val])

If val > 0, sets the internal variable holding the system HW sr.

table(table)

Returns a pointer to function table as an ndarray.

tableArgs(table)

Returns a pointer to the args used to generate a function table.

tableLength(table)

Returns the length of a function table.

unlockChannel(channel)

Unlocks access to the channel.

version()

The version number times 1000 (6.18.0 = 6180).

writeCircularBuffer(buffer, data, numitems)

Writes to circular buffer.

A4()[source]#

Returns the A4 frequency reference.

Return type:

float

APIVersion()[source]#

For compatibility, csound 7 does not implement an api version at the moment

In csound 6 there was a version for csound / libcsound and a version for the API, indicating that a new version of csound did not necessarily mean a modification of the API itself. The API version tracked changes in the API. With csound 7 this practice has been abandoned and the API version removed. This method is added for compatibility, with the version reported being the same as the csound version (returned by version())

Return type:

int

UDPServerStart(port)[source]#

Starts the UDP server on a supplied port number.

Parameters:

port (int) – port number

Return type:

int

Returns:

CSOUND_SUCCESS if ok, CSOUND_ERROR otherwise.

Note

Not present in csound 7. This is placed here for compatibility with csound 6.

In csound 7 this functionality is not exposed through the API and must be set via command-line options (--port=...). This means that the UDP server can only be started before any compilation has taken place, since options can not be set after the csound process has been started

See also

setOption()

allocatedChannels()[source]#

Returns a list of allocated channels

Return type:

list[ChannelInfo]

appendOpcode(opname, dsblksiz, flags, outypes, intypes, initfunc, perffunc, deinitfunc=None)[source]#

Appends an opcode implemented by external software.

This opcode is added to Csound’s internal opcode list.

The opcode list is extended by one slot, and the parameters are copied into the new slot.

Parameters:
  • opname (str) – opcode name

  • dsblksiz (int) – sizeof the structure used for the opcode.

  • flags (int) – flags passed, normally 0

  • outtypes – a string defining the output types of the opcode

  • intypes (str) – string defining input types

  • initfunc (Callable) – func called at init, with the form (CSOUND *, void *), where the second pointer is a pointer to a struct used for the opcode

  • perffunc (Callable) – func called at perf time, with the same form as the initfunc

  • deinitfunc (Callable) – func called at deinit, same form as initfunc

Returns:

zero on success

arrayData(adat)[source]#

Get the data from the ARRAYDAT adat.

Return type:

ndarray

arrayDataDimensions(adat)[source]#

Get the dimensions of the ARRAYDAT adat.

Return type:

int

arrayDataSizes(adat)[source]#

Get the sizes of each dimension of the ARRAYDAT adat.

Parameters:

adata – the array, a ARRAYDAT_p struct

Return type:

tuple[int, ...]

Returns:

a list of sizes, where the size of the list is the number of dimensions of the array

arrayDataType(adat)[source]#

Get the type of data the ARRAYDAT adat.

Parameters:

adata – the ARRAYDAT_p array

Return type:

str

Returns:

the array datatype as a str, one of ‘a’ (audio), ‘i’ (init), ‘k’ (control values) or ‘S’ (strings)

audioChannel(name, samples=None)[source]#

Copies the audio channel identified by name into ndarray samples.

Parameters:
  • name (str) – the name of the channel

  • samples (ndarray | None) – an array of float64 to hold the audio samples. It should be a 1D array at least ksmps in size. If not given a new array is created

Return type:

ndarray

Returns:

the np.ndarray holding the samples. If an array was passed as argument the same array is returned

audioDevList(isOutput)[source]#

List of available input and output audio devices.

Parameters:

isOutput (bool) – True to return output devices, False outputs input devices

Return type:

list[AudioDevice]

Returns:

a list of audio devices

Each item in the list is a AudioDevice with attributes deviceName, deviceId, rtModule, masNchnls, isOutput

Must be called after an orchestra has been compiled to get meaningful information.

channelDatasize(name)[source]#

Returns the size of data stored in a channel.

Parameters:

name (str) – name of the channel

Return type:

int

Returns:

size of the data.

channelInfo(name)[source]#

Query info about a channel

Parameters:

name (str) – the name of the channel

Return type:

tuple[str, int]

Returns:

a tuple (kind: str, mode: int).

If the channel does not exist kind will be an empty string and mode will be 0. Kind is one of ‘control’, ‘audio’, ‘string’, ‘pvs’ or ‘array’. Mode is 1 for input, 2 for output, 3 for input+output

channelPtr(name, kind, mode='r')[source]#

Returns a pointer to the specified channel and an error message.

Parameters:
  • name (str) – the name of the channel

  • kind (str) – one of ‘control’, ‘audio’, ‘string’

  • mode – one of ‘r’ (read=input), ‘w’ (write=output), ‘rw’ (both read and write). The mode is determined from the perspective of the csound process, so a channel declared as input (‘r’) will read information from the host, a channel declared as output (‘w’) will write information to the host.

Return type:

tuple[ndarray | c_char_p | c_void_p | None, str]

Returns:

a tuple (pointer, errormsg)

Channel Kind

Returned Pointer

control

numpy array, float64, size 1

audio

numpy array, float64, size ksmps

string

ctypes.c_char_p

pvs

ctypes.c_void_p

array

numpy array, float64 (arbitrary shape)

The error message is either an empty string or a string describing the error.

The channel is created first if it does not exist yet.

If the channel already exists, it must match the data type (control, audio, or string). The mode bits are OR’d with the new value, meaning that a channel declared in csound as input can be made to be input+output if called with ‘rw’ as mode.

Note

Operations on the pointer are not thread-safe by default. The host is required to take care of thread-safety by retrieving the channel lock with channelLock() and using spinLock() and spinUnlock() to protect access to the pointer.

Optionally, use the methods setControlChannel(), controlChannel(), setAudioChannel(), etc., which are threadsafe by default

See Top/threadsafe.c in the Csound library sources for examples.

channelVarTypeName(name)[source]#

Returns the var type for a channel name.

Parameters:

name (str) – name of the channel

Return type:

str

Returns:

The channel variable type (one of ‘control’, ‘audio’, ‘string’, ‘pvs’ or ‘array’) or an empty string if the channel does not exist

Returns None if the channel was not found. Currently supported channel var types are ‘control’, ‘audio’, ‘string’, ‘pvs’ and ‘array’

cleanup()[source]#

This is not needed in csound7, only here for compatibility

Return type:

None

compileCommandLine(*args)[source]#

Compiles csound command line arguments

As directed by the supplied command-line arguments, but does not perform them. Returns a non-zero error code on failure. In this mode, the sequence of calls should be as follows:

cs = Csound()
cs.compileCommandLine(args)
cs.perform()
cs.reset()
compileCsd(path, block=True)[source]#

Compiles a Csound input file (.csd file)

Returns a non-zero error code on failure.

Parameters:
  • path (str) – the path to the .csd file

  • block – if True, block until finished. Otherwise compilation is done asynchronously. In this case the returned value is meaningless

Return type:

int

If start() is called before this method, the <CsOptions> element is ignored (but setOption() can be called any number of times), the <CsScore> element is not pre-processed, but dispatched as real-time events; and performance continues indefinitely, or until ended by calling stop or some other logic.

Note

this function can be called repeatedly during performance to replace or add new instruments and events.

Example

cs = Csound()
cs.setOption(...)
cs.start()   # <---- start before compile, options in compiled code will be ignored
cs.compileCsd("/path/to/my.csd")
while cs.performKsmps() == CSOUND_SUCCESS:
    pass

But if this method is called before start, the <CsOptions> element is used, the <CsScore> section is pre-processed and dispatched normally, and performance terminates when the score terminates, or stop is called.

cs = Csound()
cs.setOption(...)
# No start, the <CsOption> section is honoured
cs.compileCsd("/path/to/my.csd")
# .start is called internally before performKsmps,
while cs.performKsmps() == CSOUND_SUCCESS:
    pass
cs.reset()
compileCsdText(code, block=True)[source]#

Compiles a Csound input file (.csd file) or a text string.

Parameters:
  • code (str) – the code to compile

  • block – if True, block until finished. Otherwise compilation is done asynchronously. In this case the returned value is meaningless

Return type:

int

Returns:

non-zero error code on failure.

If start() is called before this method, the <CsOptions> element is ignored (but setOption() can be called any number of times), the <CsScore> element is not pre-processed, but dispatched as real-time events; and performance continues indefinitely, or until ended by calling stop or some other logic.

Note

This function can be called repeatedly during performance to replace or add new instruments and events.

Example

>>> from libcsound import *
>>> cs = Csound()
>>> cs.setOption(...)
>>> cs.start()
>>> cs.compileCsdText(code)
>>> while not cs.performKsmps():
...     pass
>>> cs.reset()

But if this method is called before start(), the <CsOptions> element is used, the <CsScore> section is pre-processed and dispatched normally, and performance terminates when the score terminates, or stop is called.

...
cs.compileCsdText(code)
cs.start()
while not cs.performKsmps():
    pass
cs.reset()
compileOrc(orc, block=True)[source]#

Parses and compiles the given orchestra from a string.

Parameters:
  • orc (str) – the code to compile

  • block – if True, any global code will be evaluated in synchronous mode. Otherwise, this methods returns immediately but any global code passed to csound might not still be available

Return type:

int

Returns:

0 if OK, an error code otherwise

Also evaluating any global space code (i-time only) in synchronous or asynchronous (block=False) mode.

Example

cs = Csound()
cs.setOption(...)
cs.compileOrc(r'''
instr 1
    a1 rand 0dbfs/4
    out a1
endin
''')
cs.scoreEvent(...)
cs.perform()
compileOrcAsync(orc)[source]#

Async version of compileOrc().

Note

ported from csound 6 for portability. This is similar to calling compileOrc() with block=False

Parameters:

orc (str) – the code to compile

Return type:

int

Returns:

0 if OK, an error otherwise

The code is parsed and compiled, then placed on a queue for asynchronous merge into the running engine, and evaluation. The function returns following parsing and compilation.

compileOrcHeader(sr=None, nchnls=2, nchnls_i=None, zerodbfs=1.0, ksmps=64, a4=None)[source]#

Compile the orchestra header (sr, ksmps, nchnls, …)

Only those values which are explicitly given (not None) are included

Note

Values set via options are prioritized over values set in the orchestra

Parameters:
  • sr (int | None) – the sample rate

  • ksmps – samples per cycle

  • nchnls – number of output channels

  • nchnls_i (int | None) – number of input channels

  • zerodbfs – the value of 0dbfs, should be 1. for any mordern orchestra

  • a4 (int | None) – reference frequency

Return type:

None

controlChannel(name)[source]#

Retrieves the value of control channel identified by name.

Parameters:

name (str) – the name of the channel

Return type:

tuple[float, int]

Returns:

a tuple (value – float, returncode: int)

controlChannelHints(name)[source]#

Returns special parameters (if any) of a control channel.

Parameters:

name (str) – name of the channel

Return type:

tuple[ControlChannelHints | None, int]

Returns:

a tuple (hints: ControlChannelHints, errorcode: int) where hints is a ControlChannelHints struct or None if the channel does not exist.

Those parameters have been previously set with Csound.setControlChannelHints() or the chnparams opcode.

The return values are a ControlChannelHints structure and CSOUND_SUCCESS if the channel exists and is a control channel, otherwise, None and an error code are returned.

createCircularBuffer(numelem, elemsize=0)[source]#

Creates a circular buffer with numelem number of elements.

Parameters:
  • numelem (int) – number of elements in the buffer

  • elemsize (int) – size of each element, in bytes. Defaults to the size of MYFLT

Return type:

c_void_p

Returns:

the circular buffer, as an opaque pointer

The element’s size is set from elemsize. It should be used like:

>>> cs = Csound()
>>> ...
>>> circularbuf = cs.createCircularBuffer(1024, cs.sizeOfMYFLT())
createMessageBuffer(echo=False)[source]#

Creates a buffer for storing messages printed by Csound.

Should be called after creating a Csound instance. The buffer can be freed by calling destroyMessageBuffer() before deleting the Csound instance. You will generally want to call cleanup() to make sure the last messages are flushed to the message buffer before destroying Csound.

Parameters:

echo – if True, messages are also printed to stdout or stderr, depending on the type of the message, in addition to being stored in the buffer.

Return type:

None

Using the message buffer ties up the internal message callback, so setMessageCallback() should not be called after creating the message buffer.

csound()[source]#

Returns the opaque pointer to the underlying CSOUND struct.

This pointer is needed to instantiate a PerformanceThread object.

Return type:

c_void_p

currentTimeSamples()[source]#

Current performance time in samples.

Return type:

int

debug()[source]#

Returns whether Csound is set to print debug messages.

Those messages are sent through the DebugMsg() internal API function.

Return type:

bool

deleteChannelList(lst)[source]#

Releases a channel list previously returned by list_channels().

Return type:

None

destroyCircularBuffer(buffer)[source]#

Frees circular buffer.

Return type:

None

destroyMessageBuffer()[source]#

Releases all memory used by the message buffer.

Return type:

None

env(name)[source]#

Gets the value of environment variable name.

Parameters:

name (str) – the environment variable

Return type:

str | None

Returns:

the value or None if no such variable is found

The searching order is: local environment of Csound, variables set with Csound.setGlobalEnv(), and system environment variables. Should be called after compileCommandLine(). Return value is None if the variable is not set.

evalCode(code)[source]#

Evaluate the given code (blocking), returns the value passed to the return opcode

Parameters:

code (str) – the code to evaluate. This code is evaluated at the global space and is limited to init-time code

Return type:

float

Returns:

the value passed to the return opcode in global space

Example

code = '''
  i1 = 2 + 2
  return i1
'''
retval = cs.evalCode(code)

Note

Calling this method while csound is run in realtime via a performance thread might incur in high latency. To avoid this, call the evalCode() method on the performance thread

event(kind, pfields, block=True)[source]#

Send a new event.

Parameters:
  • kind (str) – the kind of event, one of ‘i’, ‘f’, ‘e’

  • params – pfields of the event, starting with p1

  • block – if True, the operation is blocking. Otherwise it is performed asynchronously

Return type:

None

Note

this method does not exist in csound 6. For backwards compatibility use scoreEvent() or scoreEventAsync()

eventString(message, block=True)[source]#

Schedule a new event as a string.

Parameters:
  • message (str) – the message to send. Multiple events separated by newlines are possible. Score preprocessing (carry, etc.) is applied

  • block – if true, the operation is run blocking

Return type:

None

Two operation modes are supported:

  1. Score events: any calls before start() add the string events to the score (block is disregarded)

  2. Realtime events: after the engine starts, string events are added to the realtime event queue

Note

This method is new in csound 7, fusing inputMessage() and inputMessageAsync() into one method. It has been ported to csound 6 for forward compatibility.

firstMessage()[source]#

Returns the first message from the buffer.

See also

readMessage() or iterMessages() for a more ergonomic method to access the message buffer

Return type:

str

firstMessageAttr()[source]#

Returns the attribute parameter of the first message in the buffer.

See also

readMessage() or iterMessages() for a more ergonomic method to access the message buffer

Return type:

int

flushCircularBuffer(buffer)[source]#

Empties circular buffer of any remaining data.

This function should only be used if there is no reader actively getting data from the buffer.

Parameters:

buffer (c_void_p) – pointer to an existing circular buffer

Return type:

None

get0dBFS()[source]#

Returns the 0dBFS level of the spin/spout buffers.

Return type:

float

hostData()[source]#

Returns host data.

Return type:

c_void_p

initArrayChannel(name, dtype, size)[source]#

Create and initialise an array channel with a given array type.

Parameters:
  • name (str) – name of the channel

  • dtype (str) – the data type of array, one of ‘a’ (audio), ‘k’ (control values), or ‘S’ (strings).

  • size (Union[int, Sequence[int]]) – the size of the array or the sizes of each dimension

Returns:

the ARRAYDAT_p for the requested channel or None on error

Note

if the channel exists and has already been initialised, this function is a non-op.

initPvsChannel(name, fftsize, overlap, winsize, wintype, format=0)[source]#

Create/initialise an Fsig channel.

Parameters:
  • name (str) – name of the channel

  • fftsize (int) – FFT analysis size

  • overlap (int) – analysis overlap size in samples

  • winsize (int) – analysis window size in samples

  • wintype (int | str) – analysis window type. One of ‘hamming’, ‘hann’, ‘kaiser’, ‘blackman’, ‘blackman-exact’, ‘nuttallc3’, ‘bharris3’, ‘bharrismin’, ‘rect’ (see pvsdat types enumeration)

  • format (int) – analysis data format (see pvsdat format enumeration)

Return type:

c_void_p | None

Returns:

the PVSDAT for the requested channel or None on error.

Note

if the channel exists and has already been initialised, this function is a non-op.

inputMessage(message)[source]#

Send a new event as a string, blocking

The syntax is the same as a score line.

Similar to eventString(), here for compatibility with csound6

Parameters:

s – a score line to send

inputMessageAsync(message)[source]#

Send a new event as a string, async

Similar to eventString() called with block=False, here for compatibility with csound6

Parameters:

s – a score line to send

Return type:

None

See also

inputMessage()

instrNumber(name)[source]#

Get the instrument number for a given instrument name string.

For use in numeric parameters list (event()).

Parameters:

name (str) – the name of the instr

Return type:

int

Returns:

The instrument number of -1 if not found

isScorePending()[source]#

Tells whether Csound score events are performed or not.

Independently of real-time MIDI events (see setScorePending()).

Return type:

bool

iterMessages()[source]#

Iterate over the messages in the message buffer

This operation empties the message buffer

Return type:

Iterator[tuple[str, int]]

Returns:

an iterator of tuples (message: str, attribute: int)

keyPress(c)[source]#

Sets the ASCII code of the most recent key pressed.

This value is used by the sensekey opcode if a callback for returning keyboard events is not set (see registerKeyboardCallback()).

killInstance(instr, mode, allowRelease=True)[source]#

Kills off one or more running instances of an instrument.

Parameters:
  • instr (float | int | str) – the instrument number or the name

  • mode (int) – which instance/instances to kill (see below)

  • allowRelease – the killed instances are allowed to stay alive to perform the release part of an amplitude envelope

Mode

Meaning

0

killall instances

1

oldest only

2

newest only

4

turnoff notes with exactly matching fractional instr number

8

turnoff notes with indefinite duration (p3 < 0)

Modes can be combined. For example 1+4 will kill the oldest event with exactly matching fractional instr. A mode of 2+8 will kill the newest event of indefinite duration matching the given instr

Note

The underlying function in the csound API has been removed in csound 7. This method implements the functionality present in csound 6 using the turnoff2 opcode directly

kr()[source]#

Number of control samples per second.

Return type:

float

ksmps()[source]#

Number of audio sample frames per control sample.

Return type:

int

listChannels()[source]#

Returns a list of allocated channels and an error message.

Note

This is a low-level function, kept here for completion and compatibility with csound 6. To list all allocated channels in a more ergonomic way see allocatedChannels()

A ControlChannelInfo object contains the channel characteristics. The error message indicates if there is not enough memory for allocating the list or it is an empty string if there is no error. In the case of no channels or an error, the list is None.

Note

The caller is responsible for freeing the list returned by the C API with deleteChannelList(). The name pointers may become invalid after calling reset().

Return type:

tuple[Array[ControlChannelInfo] | None, str]

loadPlugins(directory)[source]#

Loads all plugins from a given directory.

Parameters:

directory (str) – the path to the plugins directory

Return type:

int

Generally called immediatly after csoundCreate() to make new opcodes/modules available for compilation and performance.

lockChannel(channel)[source]#

Locks access to the channel.

Access to data is allowed in a threadsafe manner.

Return type:

None

message(message)[source]#

Displays an informational message.

Parameters:

message (str) – the message to display

messageCnt()[source]#

Returns the number of pending messages in the buffer.

Return type:

int

messageLevel()[source]#

Returns the Csound message level (from 0 to 231).

Return type:

int

messageS(attr, message)[source]#

Prints message with special attributes.

Parameters:
  • attr (int) – an integer attribute

  • message (str) – the message to display

Return type:

None

(See msg_attr.h for the list of available attributes). With attr=0, messageS() is identical to message().

midiDevList(isOutput=False)[source]#

Returns a list of available input or output midi devices.

Parameters:

isOutput – True to return output devices, False outputs input devices

Return type:

list[MidiDevice]

Returns:

a list of midi devices

Each item in the list is a dictionnary representing a device. The dictionnary keys are device_name, interface_name, device_id, midi_module (value type string), isOutput (value type boolean).

Must be called after an orchestra has been compiled to get meaningful information.

module(number)[source]#

Retrieves a module name and type given a number.

Parameters:

number (int) – a number identifying the module

Return type:

tuple[str, str, int]

Returns:

a tuple (name: str, kind: str, errcode: int)

Name is the name of the module, kind is “audio” or “midi” and errcode is CSOUND_SUCCESS on success and CSOUND_ERROR if module number was not found

Example

n = 0
while True:
    name, kind, err = cs.module(n)
    if err == ctcsound.CSOUND_ERROR:
        break
    print(f"Module {n}: {name} ({kind})")
    n += 1
modules()[source]#

Returns a list of modules

Return type:

list[tuple[str, str]]

Returns:

a list of tuples of the form (name: str, type: str), where name is the name of the module and type is one of “audio” or “midi”

See also

module()

nchnls()[source]#

Number of output channels

Return type:

int

nchnlsInput()[source]#

Number of input channels

Return type:

int

params(params=None)[source]#

Current set of parameters from a CSOUND instance.

Parameters:

params (CsoundParams | None) – if given, the destination of the params structure. Otherwise a CsoundParams struct is created and returned

Return type:

CsoundParams

Returns:

the CsoundParams structure. If given a struct as argument, that same struct is returned

See also

Csound.setParams()

These parameters are in a CsoundParams structure. See setParams():

p = CsoundParams()
cs.params(p)
peekCircularBuffer(buffer, out, numitems)[source]#

Reads from circular buffer without removing them from the buffer.

Parameters:
  • buffer (c_void_p) – pointer to an existing circular buffer

  • out (ndarray) – preallocated ndarray with at least items number of elements, where buffer contents will be read into

  • numitems (int) – number of samples to be read

Return type:

int

Returns:

The actual number of items read (0 <= n <= items).

perform()[source]#

Handles input events and performs audio output.

This is done until the end of score is reached (positive return value), an error occurs (negative return value), or performance is stopped by calling stop() from another thread (zero return value).

Return type:

int

Returns:

0 if stopped, 1 if end of score is reached, negative on error

Note that some form of compilation needs to happen before (compileCommandLine(), compileOrc(), etc.). Also any event scheduling (readScore(), scoreEvent(), etc.) needs to be done prior to calling this method.

In the case of zero return value, perform() can be called again to continue the stopped performance. Otherwise, reset() should be called to clean up after the finished or failed performance.

Note

The underlying function csoundPerform has been removed from the API in csound 7. This method is included here for backwards compatibility with csound 6 and might be removed in the future.

performKsmps()[source]#

Handles input events, and performs audio output for one cycle

This is done for one control sample worth (ksmps) of audio output.

Return type:

bool

Returns:

False during performance, True when performance is finished.

If called until it returns True, it will perform an entire score. Enables external software to control the execution of Csound, and to synchronize performance with audio input and output. start() must be called first.

performanceThread()[source]#

Creates a performance thread attached to this csound instance

Return type:

PerformanceThread

Returns:

the created performance thread object

Since there can be only one performance thread for each instance, calling this method repeatedly always returns the same thread as long as the thread has not been joint

The playback is paused at start time. It can be stopped by calling stop().

Example

from libcsound import *
cs = Csound(...)
...
perfthread = cs.performanceThread()

To stop the performance thread, call stop() and then join():

# When finished:
perfthread.stop()
perfthread.join()
popFirstMessage()[source]#

Removes the first message from the buffer.

See also

readMessage() or iterMessages() for a more ergonomic method to access the message buffer

Return type:

None

pvsData(pvsdat)[source]#

Get the analysis data frame from the PVSDAT pvsdat.

pvsDataFftSize(pvsdat)[source]#

Get the analysis FFT size used by the PVSDAT pvsdat.

Return type:

int

pvsDataFormat(pvsdat)[source]#

Get the analysis data format used by the PVSDAT pvsdat.

Return type:

int

pvsDataFramecount(pvsdat)[source]#

Get the current framecount from PVSDAT pvsdat.

Return type:

int

pvsDataOverlap(pvsdat)[source]#

Get the analysis overlap size used by the PVSDAT pvsdat.

Return type:

int

pvsDataWindowSize(pvsdat)[source]#

Get the analysis window size used by the PVSDAT pvsdat.

Return type:

int

readCircularBuffer(buffer, out, numitems)[source]#

Reads from circular buffer.

Parameters:
  • buffer (c_void_p) – pointer to an existing circular buffer

  • out (ndarray) – preallocated ndarray with at least items number of elements, where buffer contents will be read into

  • items – number of samples to be read

Return type:

int

Returns:

the actual number of items read (0 <= n <= items).

readMessage()[source]#

Reads a message from the message buffer and removes it from it

Return type:

tuple[str, int]

Returns:

a tuple (message: str, attribute: int). If there are no more messages, the message is an empty string and attribute is 0

registerKeyboardCallback(function, userdata, typemask)[source]#

Registers general purpose callback functions for keyboard events.

Parameters:
  • function – the callback

  • userData – data passed to the callback

  • typemask – the callback type, one of CSOUND_CALLBACK_KBD_EVENT or CSOUND_CALLBACK_KBD_TEXT

These callbacks are called on every control period by the sensekey opcode.

The callback is preserved on reset(), and multiple callbacks may be set and will be called in reverse order of registration. If the same function is set again, it is only moved in the list of callbacks so that it will be called first, and the user data and type mask parameters are updated. type_ can be the bitwise OR of callback types for which the function should be called, or zero for all types.

Returns zero on success, CSOUND_ERROR if the specified function pointer or type mask is invalid, and CSOUND_MEMORY if there is not enough memory.

The callback function takes the following arguments:

  • userData: the “user data” pointer, as specified when setting the callback

  • p: data pointer, depending on the callback type

  • typemask: callback type, can be one of the following (more may be added in future versions of Csound)

    • CSOUND_CALLBACK_KBD_EVENT

    • CSOUND_CALLBACK_KBD_TEXT: called by the sensekey opcode to fetch key codes. The data pointer is a pointer to a single value of type int, for returning the key code, which can be in the range 1 to 65535, or 0 if there is no keyboard event.

      For CSOUND_CALLBACK_KBD_EVENT, both key press and release events should be returned (with 65536 (0x10000) added to the key code in the latter case) as unshifted ASCII codes. CSOUND_CALLBACK_KBD_TEXT expects key press events only as the actual text that is typed.

The return value should be zero on success, negative on error, and positive if the callback was ignored (for example because the type is not known).

removeKeyboardCallback(function)[source]#

Removes a callback previously set with register_keyboard_callback().

reset()[source]#

Resets all internal memory and state.

In preparation for a new performance. Enable external software to run successive Csound performances without reloading Csound.

Return type:

None

rewindScore()[source]#

Rewinds a compiled Csound score.

It is rewinded to the time specified with setScoreOffsetSeconds().

Return type:

None

runUtility(name, args)[source]#

Runs utility with the specified name and command line arguments.

Parameters:
  • name (str) – the utility to run

  • args (list[str]) – a list of arguments to pass to it

Return type:

int

Returns:

zero if ok, an error code otherwise

Should be called after loading utility plugins. Use reset() to clean up after calling this function. Returns zero if the utility was run successfully.

scoreEvent(kind, pfields)[source]#

Send a new event

This is an alias to event(…, block=True), here for compatibility with csound 6

Parameters:
  • kind (str) – the kind of event, one of ‘i’, ‘f’, ‘e’

  • pfields (Union[Sequence[float], ndarray]) – pfields of the event, starting with p1

Return type:

int

Returns:

CSOUND_SUCCESS (0) if ok, an error otherwise

scoreEventAsync(kind, pfields)[source]#

Send a new event, async

This is an alias to csound.event(..., block=True), here for compatibility with csound 6

Parameters:
  • kind (str) – the kind of event, one of ‘i’, ‘f’, ‘e’

  • params – pfields of the event, starting with p1

Return type:

None

scoreOffsetSeconds()[source]#

Returns the score time beginning.

At this time score events will actually immediately be performed (see Csound.setScoreOffsetSeconds()).

Return type:

float

scoreTime()[source]#

Returns the current score time.

Return type:

float

Returns:

current time, in seconds

The return value is the time in seconds since the beginning of performance. This can be used to schedule events at absolute times

setArrayData(adat, data)[source]#

Set the data in the ARRAYDAT adat.

Return type:

None

setAudioChannel(name, samples)[source]#

Sets the audio channel name with data from the ndarray samples.

Parameters:
  • name (str) – the name of the channel

  • samples (ndarray) – an array of float64 to hold the audio samples. It should be a 1D array at least ksmps in size

See also

audioChannel()

setControlChannel(name, val)[source]#

Sets the value of control channel identified by name.

Parameters:
  • name (str) – name of the channel

  • val (float) – new value of the channel

Return type:

None

cs = libcsound.Csound()
...
# This will create the channel if it does not exist already
cs.setControlChannel('foo', 10)

# To modify a control channel with low latency use a performance thread
thread = cs.performanceThread()
thread.play()

# At some point, change the value with a thread task. This takes effect
# in the next cycle
thread.requestCallback(lambda csound: csound.setControlChannel('foo', 20))
setControlChannelHints(name, hints=None, behav=0, dflt=0.01, min=0.0, max=1.0, x=0, y=0, width=0, height=0, attributes=None)[source]#
Parameters:
  • name (str) – name of the channel

  • hints (ControlChannelHints | None) – the hints to set. If None, a hints structure will be constructed with the named arguments. If given, any other settings (min, max, x, …) will be ignored

  • behav (int)

Return type:

None

Returns:

CSOUND_SUCCSESS (0) if ok, CSOUND_ERROR if the channel does not exist, it is not a control channel or the parameters are invalid, CSOUND_MEMORY if could not allocate memory

These hints have no internal function but can be used by front ends to construct GUIs or to constrain values. See the ControlChannelHints structure for details.

setDebug(debug)[source]#

Sets whether Csound prints debug messages.

Parameters:

debug (bool) – if True, debugging is turned on. Otherwise debug messages are not printed

Return type:

None

The debug argument must have value True or False. Those messages come from the DebugMsg() internal API function.

setDrawGraphCallback(function)[source]#

Called by external software to set Csound’s DrawGraph function.

Return type:

None

setEndMarker(time)[source]#

Add an end event (‘e’) to the score

This stops the performance at the given time

Parameters:

time (float) – time to add the end event

Return type:

None

setExitGraphCallback(function)[source]#

Called by external software to set Csound’s ExitGraph function.

Return type:

None

setExternalMidiErrorStringCallback(function)[source]#

Sets a callback for converting MIDI error codes to strings.

setExternalMidiInCloseCallback(function)[source]#

Sets a callback for closing real time MIDI input.

setExternalMidiInOpenCallback(function)[source]#

Sets a callback for opening real-time MIDI input.

Return type:

None

setExternalMidiOutCloseCallback(function)[source]#

Sets a callback for closing real time MIDI input.

setExternalMidiOutOpenCallback(function)[source]#

Sets a callback for opening real-time MIDI input.

setExternalMidiReadCallback(function)[source]#

Sets a callback for reading from real time MIDI input.

Return type:

None

setExternalMidiWriteCallback(function)[source]#

Sets a callback for reading from real time MIDI input.

setGlobalEnv(name, value)[source]#

Set the global value of environment variable name to value.

Parameters:
  • name (str) – the name of the environment variable

  • value (str | None) – the value of the variable, or None to delete the variable

Return type:

int

Returns:

0 if successfull, non-zero otherwise

Note

It is not safe to call this function while any Csound instances are active.

setHostAudioIO()[source]#

Disable all default handling of sound I/O.

Calling this function after the creation of a Csound object and before the start of performance will disable all default handling of sound I/O by the Csound library via its audio backend module. Host application should in this case use the spin/spout buffers directly.

setHostData(data)[source]#

Sets host data.

Parameters:

data – can be any data

Return type:

None

setHostImplementedMidiIO(state)[source]#

Called with state=True disables native midi IO

In that case the host implements all midi input/output via callbacks

Note

this method is here for compatibility with csound 6. It is a proxy for Csound.setHostMidiIO()

Return type:

None

setHostMidiIO()[source]#

Disable all default handling of MIDI I/O.

Call this method before the start of performance to implement MIDI via the callbacks below.

Return type:

None

setInput(name)[source]#

Sets input source.

Parameters:

name (str) – name of the input device. Depends on the rt module used

Return type:

None

Note

The underlying API function (csoundSetInput) has been removed from csound 7. This method implements the same functionality present in the csound 6 API by means of command line options (-i). It is present here for compatibility with csound 6. (see setInput(), setOption())

setInputChannelCallback(function)[source]#

Sets the function to call whenever the invalue opcode is used.

Return type:

None

setIsGraphable(isGraphable)[source]#

Tells Csound whether external graphic table display is supported.

Return the previously set value (initially False).

Return type:

bool

setKillGraphCallback(function)[source]#

Called by external software to set Csound’s KillGraph function.

Return type:

None

setMakeGraphCallback(function)[source]#

Called by external software to set Csound’s MakeGraph function.

Return type:

None

setMessageLevel(messageLevel)[source]#

Sets the Csound message level (from 0 to 231).

Parameters:

messageLevel (int) – message level, a number between 0 and 231. TODO: explain what this means

Return type:

None

setMessageStringCallback(attr, function)[source]#

Sets an alternative message print function.

This function is to be called by Csound to print an informational message, using a less granular signature. This callback can be set for –realtime mode. This callback is cleared after reset.

setMidiDeviceListCallback(function)[source]#

Sets a callback for obtaining a list of MIDI devices.

setMidiInput(name)[source]#

Sets MIDI input device name/number.

Parameters:

name (str) – name of the input midi device

Return type:

None

Note

The underlying API function (csoundSetMidiInput) has been removed from csound 7. This method implements the same functionality present in the csound 6 API by means of command line options (--midi-device=...). It is present here for compatibility with csound 6.

setMidiModule(module)[source]#

Sets the current MIDI IO module.

Parameters:

module (str) – the name of the module. Possible modules depend on the platform and which modules have been compiled

Platform

MIDI Modules

linux

portmidi (default), alsa, jack alsaraw, alsaseq, virtual

macos

portmidi (default), cmidi (coremidi)

windows

portmidi (default), winmme

android

MIDI is not supported

Return type:

None

setOpenFileCallback(function)[source]#

Sets a callback for opening a file.

The callback is made when a file is going to be opened. The following information is passed to the callback:

Return type:

None

string

pathname of the file; either full or relative to current dir

string

access mode of the file.

Pass None to disable the callback. This callback is retained after a reset() call.

setOpenSoundFileCallback(function)[source]#

Sets a callback for opening a sound file.

The callback is made when a sound file is going to be opened. The following information is passed to the callback:

Return type:

None

string

pathname of the file; either full or relative to current dir

int

access flags for the file.

ptr

sound file info of the file.

Pass None to disable the callback. This callback is retained after a reset() call.

setOption(option)[source]#

Set csound option/options

Parameters:

option (str) – a command line option passed to the csound process. Any number of options can be passed at once, separated by whitespace

Return type:

int

Returns:

zero on success, an error code otherwise

Options can only be set before the csound process is started. Multiple options are allowed in one string.

Options

--output= (-o)

Output device or filename. -odac for realtime audio using the default device. When using jack, -odac:<portpattern>, for example -odac:"Built-in Audio Analog Stereo" will connect to all ports matching the given pattern

--input= (-i)

Input device or filename. Similar to -o

-+rtaudio=<module>

Real-time audio module, used with -odac..., possible values are portaudio, auhal (coreaudio, only in macos), alsa (linux only), jack, pulse (pulseaudio, linux)

-+rtmidi=

Real time MIDI module

--nodisplays (-d)

Supress all displays

--format=<fmt>

Soundfile format, one of wav, aiff, w64, flac, caf, ogg, mpeg

--format=<fmt>

Sample format, one of alaw, ulaw, float, double, short, long, 24bit, vorbis

--midi-device=<dev>

Read MIDI from the given device

--realtime

Realtime priority mode

--sample-accurate

Use sample-accurate timing of score events

--nosound

No sound onto disk or device

--messagelevel=N (-m)

Console message level, sum of: 1=note amps, 2=out-of-range msg, 4=warnings, 0/32/64/96=note amp format (raw,dB,colors), 128=print benchmark information. Use -m0 to disable note messages

--use-system-sr

Use the system samplerate for realtime audio. Not all audio backends define a system sr. Backends which do define system sr: jack, auhal, pulse

--get-system-sr

Print system sr and exit, requires realtime audio output (e.g. -odac) to be defined first)

--port=N

Listen to UDP port N for orchestra code (implies --daemon)

--limiter[=num]

Include clipping in audio output

--suppress-version

Do not print version info

See csound --help for a complete list of options

setOutput(name, filetype='', format='')[source]#

Sets output destination, filetype and format.

Parameters:
  • name (str) – the name of the output device/filename

  • type – in the case of a filename, the type can determine the file type used. One of “wav”, “aiff”, “au”, “raw”, “paf”, “svx”, “nist”, “voc”, “ircam”, “w64”, “mat4”, “mat5”, “pvf”, “xi”, “htk”, “sds”, “avr”, “wavex”, “sd2”, “flac”, “caf”, “wve”, “ogg”, “mpc2k”, “rf64”

  • format – only used for offline output to a filename, one of “alaw”, “schar”, “uchar”, “float”, “double”, “long”, “short”, “ulaw”, “24bit”, “vorbis”

Return type:

None

For RT audio, use device_id from CS_AUDIODEVICE for a given audio device.

Note

This is placed here for compatibility with csound6. In csound7 this functionality is not exposed through the API and must be set via command-line options (see setOption())

setOutputChannelCallback(function)[source]#

Sets the function to call whenever the outvalue opcode is used.

Return type:

None

setPvsData(pvsdat, frame)[source]#

Set the analysis data frame in the PVSDAT pvsdat.

setRTAudioModule(module)[source]#

Sets the current RT audio module.

Parameters:

module (str) – the name of the module. Possible values depend on the platform.

Platform

Modules

linux

jack, pa_cb (portaudio)

macos

au_hal (coreaudio), pa_cb, jack

windows

pa_cb (portaudio), winmm

Return type:

None

setScoreOffsetSeconds(time)[source]#

Csound score events prior to the specified time are not performed.

Parameters:

time (float) – the new time offset, in seconds

Return type:

None

Performance begins immediately at the specified time (real-time events will continue to be performed as they are received). Can be used by external software, such as a VST host, to begin score performance midway through a Csound score, for example to repeat a loop in a sequencer, or to synchronize other events with the Csound score.

setScorePending(pending)[source]#

Sets whether Csound score events are performed or not.

Real-time events will continue to be performed. Can be used by external software, such as a VST host, to turn off performance of score events (while continuing to perform real-time events), for example to mute a Csound score while working on other tracks of a piece, or to play the Csound instruments live.

Return type:

None

setStringChannel(name, string)[source]#

Sets the string channel identified by name with string.

Parameters:
  • name (str) – name of the channel

  • string (str) – new value of the channel

Return type:

None

setStringData(sdata, string)[source]#

Set a STRINGDAT structure with a null-terminated string.

sizeOfMYFLT()[source]#

Size of MYFLT in bytes.

Return type:

int

sleep(milliseconds)[source]#

Waits for at least the specified number of milliseconds.

Parameters:

milliseconds (int) – the number of milliseconds to sleep

Return type:

None

It yields the CPU to other threads.

spin()[source]#

Returns the Csound audio input working buffer (spin) as an ndarray.

Enables external software to write audio into Csound before calling perform_ksmps().

Return type:

ndarray

spout()[source]#

Returns the audio output working buffer (spout) as a numpy array

The returned array is not a copy but the actual audio data, any modification to this data will modify the output of csound.

Enables external software to read audio from Csound after calling performKsmps().

Return type:

ndarray

sr()[source]#

Returns the number of audio sample frames per second.

Return type:

float

start()[source]#

Prepares Csound for performance.

Returns:

CSOUND_SUCCESS (0) if ok, an error code otherwise

Normally called after compiling a csd file or an orc file, in which case score preprocessing is performed and performance terminates when the score terminates.

However, if called before compiling any csound code (either by compiling a csd file or orc code), score preprocessing is not performed and “i” statements are dispatched as real-time events. In this case, any options given as part of the <CsOptions> section are ignored: options can only be set prior to starting the csound process

Note

This method is called internally by methods like compileCommandLine(), perform(), performKsmps(), performBuffer(), or when a performance thread is created for this csound instance and the thread itself is started via its play() method.

stop()[source]#

Only here for compatibility, not exposed in csound7

Return type:

None

stringChannel(name)[source]#

Return a string from the string channel identified by name.

stringData(sdata)[source]#

Get a null-terminated string from a STRINGDAT structure.

systemSr(val=0.0)[source]#

If val > 0, sets the internal variable holding the system HW sr.

Parameters:

val (float) – if given, sets the system sr to this value

Return type:

float

Returns:

the stored value containing the system HW sr.

table(table)[source]#

Returns a pointer to function table as an ndarray.

Parameters:

table (int) – table number

Return type:

ndarray | None

Returns:

a numpy array sharing the memory of the table, None if the table does not exist

Any modification to the returned array will modify the table itself. I

tableArgs(table)[source]#

Returns a pointer to the args used to generate a function table.

The pointer is returned as an ndarray. If the table does not exist, None is returned.

Note

the argument list starts with the GEN number and is followed by its parameters. eg. f 1 0 1024 10 1 0.5 yields the list [10.0, 1.0, 0.5]

Return type:

ndarray | None

tableLength(table)[source]#

Returns the length of a function table.

Parameters:

table (int) – table number

Return type:

int

Returns:

the length of the table, -1 of the table does not exist

The returned length does not include the guard point

unlockChannel(channel)[source]#

Unlocks access to the channel.

It allows access to data from elsewhere.

version()[source]#

The version number times 1000 (6.18.0 = 6180).

Return type:

int

writeCircularBuffer(buffer, data, numitems)[source]#

Writes to circular buffer.

Parameters:
  • buffer (c_void_p) – pointer to an existing circular buffer

  • data (ndarray) – ndarray with at least items number of elements to be written into circular buffer

  • numitems (int) – number of samples to write

Return type:

int

Returns:

The actual number of items written (0 <= n <= items).

class libcsound.api7.PerformanceThread(csound)[source]#

Runs Csound in a separate thread.

Parameters:

csound (Csound) – the Csound instance managed by this thread

The playback is paused at start time. It can be stopped by calling stop().

Note

The recommended way to create a performance thread is to call the performanceThread() method

from libcsound import *
cs = Csound(...)
...
perfthread = PerformanceThread(cs)
...

Or simply:

perfthread = cs.performanceThread()

To stop the performance thread, call stop() and then join():

# When finished:
perfthread.stop()
perfthread.join()

Methods:

compileOrc(code)

Compile the given orchestra code

csoundPtr()

Returns the Csound instance pointer.

evalCode(code[, callback, timeout])

Similar to Csound.evalCode(), run within the context of the performance thread

flushMessageQueue()

Waits until all pending messages are actually received.

flushProcessQueue([timeout])

Wait until all process queue tasks have been acted upon

inputMessage(s)

Sends a score event as a string, similarly to line events.

isRunning()

True if the performance thread is running, False otherwise.

join()

Waits until the performance is finished or fails.

pause()

Pauses performance (can be continued by calling play()).

play()

Continues performance if it was paused.

processCallback()

Returns the process callback.

processQueueTask(func)

Add a task to the process queue, to be picked up by the process callback

record(filename, samplebits, numbufs)

Starts recording the output from Csound.

requestCallback(callback)

Calls the given callback within the performance loop

scoreEvent(abstime, kind, pfields)

Sends a score event.

setEndMarker(time[, absolute])

Add an end event to the score

setProcessCallback(function[, data])

Sets the process callback.

setProcessQueue()

Setup a queue to pprocess tasks within the performance loop

setScoreOffsetSeconds(time)

Sets the playback time pointer to the specified value (in seconds).

status()

Returns the current status.

stop()

Stops performance (cannot be continued).

stopRecord()

Stops recording and closes audio file.

togglePause()

Pauses or continues performance, depending on current state.

compileOrc(code)[source]#

Compile the given orchestra code

Parameters:

code (str) – the code to compile

Return type:

None

This method queues a compilation event within the context of this thread. The main difference with just calling compileOrc() on the Csound object is that this compilation takes place within the performance loop, reducing latency

csoundPtr()[source]#

Returns the Csound instance pointer.

Return type:

c_void_p

evalCode(code, callback=None, timeout=5.0)[source]#

Similar to Csound.evalCode(), run within the context of the performance thread

Parameters:
  • code (str) – the code to evaluate. It must end with a return statement, returning one scalar value

  • callback (Optional[Callable[[float], None]]) – if given, the function is called with the generated value and this method runs non-blocking. Otherwise this method blocks until the code is evaluated and the resulting value is returned

  • timeout – if the callback does not return after this amount of time (in seconds) a TimeoutError exeption is raised

Return type:

float

Returns:

the evaluated value if callback was not given, 0. otherwise

Note

This method was introduced in csound >= 7.0.

Example

Allocate an empty table, return the table number. This will block for at least the duration of one performance cycle. The same code evaluated directly by Csound.evalCode() might result in a much higher latency when csound is run using a performance thread

csound = Csound()
csound.compileOrc(...)
thread = csound.performanceThread()
tabnum = thread.evalCode(r'''
gi__tabnum ftgen 0, 0, 1024, -2, 0
return gi__tabnum
''')
flushMessageQueue()[source]#

Waits until all pending messages are actually received.

(pause, send score event, etc.)

flushProcessQueue(timeout=None)[source]#

Wait until all process queue tasks have been acted upon

Parameters:

timeout (float | None) – if given, a max. amount of time to wait

Return type:

None

Note

This method is only available if the process queue was set (see setProcessQueue())

inputMessage(s)[source]#

Sends a score event as a string, similarly to line events.

Parameters:

s (str) – the input message (a line within a score)

isRunning()[source]#

True if the performance thread is running, False otherwise.

Return type:

bool

join()[source]#

Waits until the performance is finished or fails.

Return type:

int

Returns:

positive if the end of score was reached or stop() was called, negative if an error occured.

Releases any resources associated with the performance thread object.

pause()[source]#

Pauses performance (can be continued by calling play()).

Return type:

None

play()[source]#

Continues performance if it was paused.

processCallback()[source]#

Returns the process callback.

processQueueTask(func)[source]#

Add a task to the process queue, to be picked up by the process callback

Parameters:

func (Callable[[Csound], Any]) – a function of the form (csound: Csound) -> None, which can access the csound API. Any returned value from the callback is ignored

Return type:

None

Note

This method is only available if the process queue was set (via setProcessQueue()). In csound 7 it is advisable to use requestCallback() instead of setting a process queue.

Example

Allocate a table in csound and return the assigned table number and a numpy array pointing to the table data

import queue
cs = Csound()
cs.compileOrc(...)
thread = cs.performanceThread()
thread.setProcessQueue()

sndfile = "/path/to/sndfile.wav"
q = queue.SimpleQueue()

def mytask(cs, q=q):
    tabnum = cs.evalCode(fr'''
    gi__tabnum ftgen 0, 0, -1, "{sndfile}", 0, 0, 0
    return gi__tabnum''')
    tabpointer = csound.table(tabnum)
    q.put((tabnum, tabpointer))

thread.processQueueTask(mytask)
tabnum, tabpointer = q.get(block=True)

See also

evalCode()

record(filename, samplebits, numbufs)[source]#

Starts recording the output from Csound.

Parameters:
  • filename (str) – the output soundfile

  • samplebits (int) – number of bits per sample (16, 24, 32)

  • numbufs (int) – number of buffers

The sample rate and number of channels are taken directly from the running Csound instance.

requestCallback(callback)[source]#

Calls the given callback within the performance loop

Parameters:

callback (Callable[[Csound], None]) – function of the form (Csound) -> None. Can access the Csound instance through the csound attribute

Return type:

None

The main advantage of using this method instead of accessing the API directly via the Csound object is that, when csound is run with a performance thread, any direct access to the API can result in extra long latency.

Note

This method was introduced in csound >= 7.0. In csound 6 a similar effect can be achieved by setting a process queue (see setProcessQueue()) and calling processQueueTask()

To pass extra arguments to the callback you can use early binding (see the example)

Example

from libcsound import *
import queue

csound = Csound(...)
thread = csound.performanceThread()

# Create an empty table of 100 elements, let csound assign a number
thread.compileOrc('gi__tab1 ftgen 0, 0, -100, -2, 0')

# Get a pointer to it, as an alternative to csound.table(...)
q = queue.SimpleQueue()
def func(csound, q=q):
    tabnum = int(csound.evalCode('return gi__tab1'))
    q.put((tabnum, pt.csound.table(tabnum)))
thread.requestCallback(func)
# This blocks until the callback has been called
tabnum, tabarr = q.get()

See also

evalCode()

scoreEvent(abstime, kind, pfields)[source]#

Sends a score event.

The event has type kind (e.g. ‘i’ for a note event).

Parameters:
  • abstime (bool) – if True, the start time of the event is measured from the beginning of performance, instead of the default of relative to the current time

  • kind (str) – the event kind, one of ‘i’, ‘f’, ‘e’, …

  • pfields (Union[Sequence[float], ndarray]) – a tuple, a list, or an ndarray of MYFLTs with all the pfields

setEndMarker(time, absolute=False)[source]#

Add an end event to the score

This stops the performance at the given time

Parameters:
  • time (float) – time to add the end event

  • absolute – if True, use absolute time

Return type:

None

setProcessCallback(function, data=None)[source]#

Sets the process callback.

Parameters:
  • function (Callable[[c_void_p], None]) – a function of the form (data: void) -> None

  • data – can be anything

Return type:

None

The callback is called with a pointer to the data passed as data

setProcessQueue()[source]#

Setup a queue to pprocess tasks within the performance loop

This is useful if access to the csound API is needed during a performance (code compilation, table access, etc), since when a performance thread is active any access to the API can result in high latency.

Note

this sets up the process callback.

setScoreOffsetSeconds(time)[source]#

Sets the playback time pointer to the specified value (in seconds).

Parameters:

time (float) – playback time in seconds

Return type:

None

status()[source]#

Returns the current status.

Zero if still playing, positive if the end of score was reached or performance was stopped, and negative if an error occured.

Return type:

int

stop()[source]#

Stops performance (cannot be continued).

Return type:

None

stopRecord()[source]#

Stops recording and closes audio file.

togglePause()[source]#

Pauses or continues performance, depending on current state.

Return type:

None