Csound API, version 6

Contents

Csound API, version 6#

This reference is valid for versions of csound >= 6.18 and prior to version 7, a The correct API is imported automatically based in the version of csound installed in the system.

In general it can be said that the csound API has been reduced for csound 7. All methods which have been discontinued in csound 7 are marked in the documentation.

Csound([hostData, opcodeDir, pointer])

Creates an instance of Csound.

PerformanceThread(csound)

Performs a score in a separate thread until the end of score is reached.


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

Creates an instance of Csound.

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

Methods:

A4()

Returns the A4 frequency reference.

APIVersion()

Returns the API version number x 100 (1.00 = 100).

CPUTime(timerStruct)

Returns the elapsed CPU time (in seconds).

UDPConsole(addr, port, mirror)

Turns on the transmission of console messages to UDP on addr:port.

UDPServerClose()

Closes the UDP server.

UDPServerStart(port)

Starts the UDP server on a supplied port number.

UDPServerStatus()

Returns the port number on which the server is running.

addSpinSample(frame, channel, sample)

Adds the indicated sample into the audio input working buffer (spin).

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

Appends an opcode implemented by external software.

audioChannel(name, samples)

Copies the audio channel identified by name into ndarray samples.

audioDevList(isOutput)

Returns a list of available input or output audio devices.

channelDatasize(name)

Returns the size of data stored in a channel.

channelInfo(name)

Query info about a channel

channelLock(name)

Recovers a pointer to a lock for the specified channel called name.

channelPtr(name, kind[, mode])

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

cleanup()

Prints information and closes audio and MIDI devices.

clearSpin()

Clears the input buffer (spin).

closeLibrary(library)

Platform-independent function to unload a shared library.

compileArgs(*args)

Compiles args.

compileCommandLine(*args)

Compiles Csound input files (such as an orchestra and score).

compileCsd(path[, block])

Compiles a Csound input file (.csd file).

compileCsdText(code[, block])

Compiles a Csound input file contained in a string of text.

compileOrc(orc[, block])

Compiles the given orchestra code

compileOrcAsync(orc)

Async version of compileOrc().

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

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

compileTree(tree)

Compiles the given TREE node into structs for Csound to use.

compileTreeAsync(tree)

Asynchronous version of compileTree().

controlChannel(name)

Retrieves the value of control channel identified by name.

controlChannelHints(name)

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

createBarrier(maxthreads)

Creates a Thread Barrier.

createCircularBuffer(numelem[, elemsize])

Creates a circular buffer with numelem number of elements.

createGlobalVariable(name, nbytes)

Allocates nbytes bytes of memory.

createMessageBuffer([echo])

Creates a buffer for storing messages printed by Csound.

createMutex(isRecursive)

Creates and returns a mutex object, or None if not successful.

createThread(function, userdata)

Creates and starts a new thread of execution.

createThread2(function, stack, userdata)

Creates and starts a new thread of execution with a user-defined stack size.

createThreadLock()

Creates and returns a monitor object, or None if not successful.

csound()

Returns the opaque pointer to the running Csound instance.

currentThreadId()

Returns the ID of the currently executing thread, or None for failure.

currentTimeSamples()

Returns the current performance time in samples.

debug()

Returns whether Csound is set to print debug messages.

deleteChannelList(lst)

Releases a channel list previously returned by listChannels().

deleteTree(tree)

Frees the resources associated with the TREE tree.

destroyBarrier(barrier)

Destroys a Thread Barrier.

destroyCircularBuffer(buffer)

Frees circular buffer.

destroyGlobalVariable(name)

Frees memory allocated for name and remove name from the database.

destroyMessageBuffer()

Releases all memory used by the message buffer.

destroyMutex(mutex)

Destroys the indicated mutex object.

destroyThreadLock(lock)

Destroys the indicated monitor object.

disposeOpcodeList(lst)

Releases an opcode list.

env(name[, withCsoundInstance])

Gets the value of environment variable name.

evalCode(code)

Parses and compiles an orchestra given on an string, synchronously.

eventString(message[, block])

Send 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.

getLibrarySymbol(library, symbolName)

Platform-independent function to get a symbol address in a shared library.

getOpcodes()

Get a list of all defined opcodes

hostData()

Returns host data.

initTimerStruct(timerStruct)

Initializes a timer structure.

inputBuffer()

Returns the Csound audio input buffer as an ndarray.

inputBufferSize()

Returns the number of samples in Csound's input buffer.

inputMessage(message)

Send a new event as a string, blocking

inputMessageAsync(message)

Asynchronous version of inputMessage()

inputName()

Returns the audio input name (-i)

isNamedGEN(num)

Checks if a given GEN number num is a named GEN.

isScorePending()

Tells whether Csound score events are performed or not.

iterMessages()

Iterate over the messages in the message buffer

joinThread(thread)

Waits until the indicated thread's routine has finished.

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()

Returns the number of control samples per second.

ksmps()

Returns the number of audio sample frames per control sample.

listChannels()

Returns a pointer and an error message.

listUtilities()

Returns a list of registered utility names.

loadPlugins(directory)

Loads all plugins from a given directory.

lockMutex(mutex)

Acquires the indicated mutex object.

lockMutexNoWait(mutex)

Acquire the indicated mutex object.

message(fmt, *args)

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, fmt, *args)

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

namedGEN(num, nameLen)

Gets the GEN name from a GEN number, if this is a named GEN.

namedGens()

Finds the list of named gens

nchnls()

Returns the number of audio output channels.

nchnlsInput()

Returns the number of audio input channels.

newOpcodeList()

Gets an alphabetically sorted list of all opcodes.

notifyThreadLock(lock)

Notifies the indicated monitor object.

openLibrary(libraryPath)

Platform-independent function to load a shared library.

outputBuffer()

Returns the Csound audio output buffer as an ndarray.

outputBufferSize()

Returns the number of samples in Csound's output buffer.

outputFormat()

Gets output type and format.

outputName()

Returns the audio output name (-o)

params([params])

Gets the current set of parameters from a CSOUND instance.

parseOrc(orc)

Parses the given orchestra from string into a TREE.

peekCircularBuffer(circularBuffer, out, numitems)

Reads from circular buffer without removing them from the buffer.

perform()

Handles input events and performs audio output.

performBuffer()

Performs Csound, sensing real-time and score events.

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.

pvsChannel(fout, name)

Receives a PvsdatExt fout from the pvsout opcode (f-rate) at channel name.

queryGlobalVariable(name)

Gets pointer to space allocated with the name name.

queryGlobalVariableNoCheck(name)

This function is the similar to :py:meth`queryGlobalVariable()`.

rand31(seed)

Simple linear congruential random number generator

randMT(state)

Returns next random number from MT19937 generator.

randomSeedFromTime()

Returns a 32-bit unsigned integer to be used as seed from current time.

readCircularBuffer(buffer, out, numitems)

Reads from circular buffer.

readMessage()

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

readScore(sco)

Reads, preprocesses, and loads a score from a string

readScoreAsync(sco)

Asynchronous version of readScore().

realTime(timerStruct)

Returns the elapsed real time (in seconds).

registerKeyboardCallback(function, userdata, ...)

Registers general purpose callback functions for keyboard events.

registerSenseEventCallback(function, userData)

Registers a function to be called by sensevents().

removeKeyboardCallback(function)

Removes a callback previously set with registerKeyboardCallback().

reset()

Resets all internal memory and state.

rewindScore()

Rewinds a compiled Csound score.

rtPlayUserData()

Returns pointer to user data pointer for real time audio output.

rtRecordUserData()

Returns pointer to user data pointer for real time audio input.

runCommand(args, noWait)

Runs an external command with the arguments specified in list args.

runUtility(name, args)

Runs utility with the specified name and command line arguments.

scoreEvent(kind, pfields)

Sends a new score event (blocking)

scoreEventAbsolute(kind, pfields[, timeOffset])

Like scoreEvent(), this function inserts a score event.

scoreEventAbsoluteAsync(type_, pfields[, ...])

Asynchronous version of scoreEventAbsolute().

scoreEventAsync(kind, pfields)

Asynchronous version of scoreEvent().

scoreOffsetSeconds()

Returns the score time beginning midway through a Csound score.

scoreTime()

Returns the current score time.

seedRandMT(initKey)

Initializes Mersenne Twister (MT19937) random number generator.

setAudioChannel(name, samples)

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

setAudioDevListCallback(function)

Sets a callback for obtaining a list of audio devices.

setControlChannel(name, val)

Sets the value of control channel identified by name.

setControlChannelHints(name, hints)

Sets parameters hints for a control channel.

setCscoreCallback(function)

Sets an external callback for Cscore processing.

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 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.

setFileOpenCallback(function)

Sets a callback for receiving notices whenever Csound opens a file.

setGlobalEnv(name, value)

Sets the global value of environment variable name to value.

setHostData(data)

Sets host data.

setHostImplementedAudioIO(state[, bufSize])

Sets user handling of sound I/O.

setHostImplementedMidiIO(state)

Called with state True if the host is implementing via callbacks.

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.

setLanguage(langcode)

Sets language to langcode.

setMakeGraphCallback(function)

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

setMessageLevel(messageLevel)

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

setMidiDevListCallback(function)

Sets a callback for obtaining a list of Midi devices.

setMidiFileInput(name)

Sets Midi file input name.

setMidiFileOutput(name)

Sets Midi file output name.

setMidiInput(name)

Sets Midi input device name/number.

setMidiModule(module)

Sets the current Midi IO module.

setMidiOutput(name)

Sets Midi output device name/number.

setOption(option)

Set csound option/options

setOutput(name[, filetype, format])

Sets output destination, type and format.

setOutputChannelCallback(function)

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

setParams(params)

Configures Csound with a given set of parameters.

setPlayOpenCallback(function)

Sets a callback for opening real-time audio playback.

setPvsChannel(fin, name)

Sends a PvsdatExt fin to the pvsin opcode (f-rate) for channel name.

setRTAudioModule(module)

Sets the current RT audio module.

setRecordOpenCallback(function)

Sets a callback for opening real-time audio recording.

setRtCloseCallback(function)

Sets a callback for closing real-time audio playback and recording.

setRtPlayCallback(function)

Sets a callback for performing real-time audio playback.

setRtRecordCallback(function)

Sets a callback for performing real-time audio recording.

setScoreOffsetSeconds(time)

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

setScorePending(pending)

Sets whether Csound score events are performed or not.

setSpinSample(frame, channel, sample)

Sets the audio input working buffer (spin) to the indicated sample.

setStringChannel(name, string)

Sets the string channel identified by name with string.

setYieldCallback(function)

Called by external software to set a yield function.

sizeOfMYFLT()

Returns the 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.

spinLock(spinlock)

Locks the spinlock.

spinLockInit(spinlock)

Inits the spinlock.

spinTryLock(spinlock)

Tries the spinlock.

spinUnlock(spinlock)

Unlocks the spinlock.

spout()

Returns the address of the Csound audio output working buffer (spout).

spoutSample(frame, channel)

Returns one sample from the Csound audio output working buf (spout).

sr()

Returns the number of audio sample frames per second.

start()

Prepares Csound for performance.

stop()

Stops a perform() running in another thread.

stopUDPConsole()

Stops transmitting console messages via UDP.

stringChannel(name)

Get a string from the given channel

systemSr([val])

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

table(table)

Returns a pointer to function as an ndarray.

tableArgs(table)

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

tableCopyIn(table, src)

Copies the contents of an ndarray src into a given function table.

tableCopyInAsync(table, src)

Asynchronous version of tableCopyIn().

tableCopyOut(table, dest)

Copies the contents of a function table into a supplied ndarray dest.

tableCopyOutAsync(table, dest)

Asynchronous version of tableCopyOut().

tableGet(table, index)

Returns the value of a slot in a function table.

tableLength(table)

Returns the length of a function table.

tableSet(table, index, value)

Sets the value of a slot in a function table.

unlockMutex(mutex)

Releases the indicated mutex object.

utilityDescription(name)

Gets utility description.

version()

Returns the version number x 1000 (6.18.0 = 6180).

waitBarrier(barrier)

Waits on the thread barrier.

waitThreadLock(lock, milliseconds)

Waits on the indicated monitor object for the indicated period.

waitThreadLockNoTimeout(lock)

Waits on the indicated monitor object until it is notified.

writeCircularBuffer(buffer, data, numitems)

Writes to circular buffer.

A4()[source]#

Returns the A4 frequency reference.

Return type:

float

APIVersion()[source]#

Returns the API version number x 100 (1.00 = 100).

Return type:

int

CPUTime(timerStruct)[source]#

Returns the elapsed CPU time (in seconds).

The time is measured since the specified timer structure was initialised.

Note

not present in csound 7

Return type:

int

UDPConsole(addr, port, mirror)[source]#

Turns on the transmission of console messages to UDP on addr:port.

Parameters:
  • addr (str) – the udp address, as a string

  • port (int) – the port number

  • mirror (bool) – if True, messages will continue to be sent to the usual destination (see setMessageCallback()) as well as to UDP.

Return type:

int

Returns:

CSOUND_SUCCESS if ok, CSOUND_ERROR otherwise

Note

This method is not present in csound 7

UDPServerClose()[source]#

Closes the UDP server.

Return type:

int

Returns:

CSOUND_SUCCESS on success, CSOUND_ERROR otherwise.

Note

This method is not present in csound 7

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

This method is not present in csound 7. To start csound with a UDP server listening for commands use the command line options (--port=<udpport>)

UDPServerStatus()[source]#

Returns the port number on which the server is running.

Return type:

int

Returns:

CSOUND_SUCCESS if running, CSOUND_ERROR otherwise

Note

This method is not present in csound 7

addSpinSample(frame, channel, sample)[source]#

Adds the indicated sample into the audio input working buffer (spin).

This only ever makes sense before calling performKsmps(). The frame and channel must be in bounds relative to ksmps() and nchnlsInput().

Note

The spin buffer needs to be cleared at every k-cycle by calling clearSpin().

Parameters:
  • frame (int) – frame number

  • channel (int) – channel number

  • sample (float) – sample value

Return type:

None

Note

Not present in csound 7

appendOpcode(opname, dsblksiz, flags, thread, outypes, intypes, iopfunc, kopfunc, aopfunc)[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 – opcode name

  • dsblksizsizeof the structure used for the opcode.

  • flags – flags passed, normally 0

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

  • intypes – string defining input types

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

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

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

Returns:

zero on success

audioChannel(name, samples)[source]#

Copies the audio channel identified by name into 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. If not given a new array is created

Return type:

None

Returns:

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

audioDevList(isOutput)[source]#

Returns a list of available input or output audio devices.

Parameters:

isOutput (bool) – True for listing output devices, False for input

Return type:

list[AudioDevice]

Returns:

a list of AudioDevice

Each item in the list is a dictionnary representing a device. The dictionnary keys are deviceName, deviceId, rtModule (value type string), maxNchnls (value type int), and isOutput (value type boolean).

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) – the name of the channel

Return type:

int

For string channels this might change if the channel space gets reallocated. Since string variables use dynamic memory allocation in Csound6, this function can be called to get the space required for stringChannel().

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

channelLock(name)[source]#

Recovers a pointer to a lock for the specified channel called name.

The returned lock can be locked/unlocked with the spinLock() and spinUnLock() functions. Returns the address of the lock or NULL if the channel does not exist.

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.

cleanup()[source]#

Prints information and closes audio and MIDI devices.

Note

after calling cleanup(), the operation of the perform function is undefined.

Return type:

None

clearSpin()[source]#

Clears the input buffer (spin).

Note

Not present in csound 7

Return type:

None

closeLibrary(library)[source]#

Platform-independent function to unload a shared library.

Note

Not present in csound 7

Return type:

int

compileArgs(*args)[source]#

Compiles args.

Reads arguments, parses and compiles an orchestra, reads, processes and loads a score.

Parameters:

args (str) – the arguments to compile, as passed to a csound executable

compileCommandLine(*args)[source]#

Compiles Csound input files (such as an orchestra and score).

Parameters:

args – any command line arg passed to csound

Return type:

int

Returns:

0 on success, an error code on failure

Compiles any csd or orc files as directed by the supplied command-line arguments, but does not perform them. Returns a non-zero error code on failure. This function cannot be called during performance, and before a repeated call, reset() needs to be called.

Example

cs.compileCommandLine(args)
while cs.performBuffer() == 0:
    pass
cs.cleanup()
cs.reset()

Calls start() internally.

compileCsd(path, block=True)[source]#

Compiles a Csound input file (.csd file).

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

  • block – dummy argument, this functions is always blocking in csound6

Return type:

int

Returns:

CSOUND_SUCCESS (0) if ok, an error code otherwise

The input file includes command-line arguments, but does not perform the file. Returns a non-zero error code on failure.

Example

cs.compileCsd(csdfile)
while cs.performBuffer() == 0:
    pass
cs.cleanup()
cs.reset()

Note

This function can be called during performance to replace or add new instruments and events. On a first call and if called before start(), this function behaves similarly to compileCommandLine().

compileCsdText(code, block=True)[source]#

Compiles a Csound input file contained in a string of text.

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

  • block – dummy argument, this functions is always blocking in csound6

Return type:

int

Returns:

0 if ok, a non-zero code on failure

The string of text includes command-line arguments, orchestra, score, etc., but it is not performed. Returns a 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.

Example

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

Note

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

compileOrc(orc, block=True)[source]#

Compiles the given orchestra code

Note

backported from csound 7

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

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().

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.

Parameters:

orc (str) – the orchestra code to compile

Return type:

int

Returns:

CSOUND_SUCCESS (0) if ok, an error code otherwise

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

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

Parameters:
  • sr (int | None) – the sample rate. Only included if given

  • 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 – reference frequency

compileTree(tree)[source]#

Compiles the given TREE node into structs for Csound to use.

This can be called during performance to compile a new TREE.

Parameters:

tree (c_void_p) – a void pointer representing a tree structure, as returned from Csound.parseOrc()

Return type:

None

Note

this method and the underlying functionality are not present in csound 7

compileTreeAsync(tree)[source]#

Asynchronous version of compileTree().

Parameters:

tree (c_void_p) – the tree to compile

Return type:

int

Returns:

CSOUND_SUCCESS (0) if ok, an error code otherwise

Note

this method and the underlying functionality are not present in csound 7

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.

Those parameters have been previously set with 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.

Return type:

tuple[ControlChannelHints | None, int]

createBarrier(maxthreads)[source]#

Creates a Thread Barrier.

Parameters:

maxthreads (int) – should be equal to the number of child threads using the barrier plus one for the master thread.

Return type:

c_void_p | None

Returns:

the barrier as an opaque pointer, or None if failed

Note

not present in csound 7

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())
createGlobalVariable(name, nbytes)[source]#

Allocates nbytes bytes of memory.

This memory can be accessed later by calling :py:meth`queryGlobalVariable()` with the specified name; the space is cleared to zero.

Returns CSOUND_SUCCESS on success, CSOUND_ERROR in case of invalid parameters (zero nbytes, invalid or already used name), or CSOUND_MEMORY if there is not enough memory.

Note

not present in csound 7

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.

createMutex(isRecursive)[source]#

Creates and returns a mutex object, or None if not successful.

Mutexes can be faster than the more general purpose monitor objects returned by createThreadLock() on some platforms, and can also be recursive, but the result of unlocking a mutex that is owned by another thread or is not locked is undefined.

If isRecursive’ id True, the mutex can be re-locked multiple times by the same thread, requiring an equal number of unlock calls; otherwise, attempting to re-lock the mutex results in undefined behavior.

Note: the handles returned by createThreadLock() and createMutex() are not compatible.

Note

not present in csound 7

Return type:

c_void_p | None

createThread(function, userdata)[source]#

Creates and starts a new thread of execution.

Returns an opaque pointer that represents the thread on success, or None for failure. The userdata pointer is passed to the thread routine.

Note

not present in csound 7

createThread2(function, stack, userdata)[source]#

Creates and starts a new thread of execution with a user-defined stack size.

Returns an opaque pointer that represents the thread on success, or None for failure. The userdata pointer is passed to the thread routine.

Note

not present in csound 7

createThreadLock()[source]#

Creates and returns a monitor object, or None if not successful.

The object is initially in signaled (notified) state.

Note

not present in csound 7

Return type:

c_void_p | None

csound()[source]#

Returns the opaque pointer to the running Csound instance.

Raises RuntimeError if the internal pointer is None. This might happen if this method is being called after the csound instance has been deleted

Return type:

c_void_p

currentThreadId()[source]#

Returns the ID of the currently executing thread, or None for failure.

NOTE: The return value can be used as a pointer to a thread object, but it should not be compared as a pointer. The pointed to values should be compared, and the user must free the pointer after use.

Note

not present in csound 7

Return type:

int | None

currentTimeSamples()[source]#

Returns the 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 listChannels().

deleteTree(tree)[source]#

Frees the resources associated with the TREE tree.

Parameters:

tree (c_void_p) – the tree to delete

Return type:

None

This function should be called whenever the TREE was created with parseOrc() and memory can be deallocated.

Note

this method and the underlying functionality are not present in csound 7

destroyBarrier(barrier)[source]#

Destroys a Thread Barrier.

Note

not present in csound 7

Return type:

int

destroyCircularBuffer(buffer)[source]#

Frees circular buffer.

Return type:

None

destroyGlobalVariable(name)[source]#

Frees memory allocated for name and remove name from the database.

Return value is CSOUND_SUCCESS on success, or CSOUND_ERROR if the name is not defined.

Note

Not implemented in csound 7

destroyMessageBuffer()[source]#

Releases all memory used by the message buffer.

Return type:

None

destroyMutex(mutex)[source]#

Destroys the indicated mutex object.

Parameters:

mutex (c_void_p) – the mutex, as returned by createMutex()

Destroying a mutex that is currently owned by a thread results in undefined behavior.

Note

not present in csound 7

destroyThreadLock(lock)[source]#

Destroys the indicated monitor object.

Note

not present in csound 7

disposeOpcodeList(lst)[source]#

Releases an opcode list.

env(name, withCsoundInstance=True)[source]#

Gets the value of environment variable name.

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

  • withCsoundInstance – if True, the local environment of the current instance is taken into account. Should be called after compileCommandLine()

Return type:

str | None

Returns:

the value of the variable, or None if it is not set

The searching order is:

  1. Local environment of Csound (if withCsoundInstance is True)

  2. Variables set with setGlobalEnv(),

  3. System environment variables.

evalCode(code)[source]#

Parses and compiles an orchestra given on an string, synchronously.

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 = r'''
  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.

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

Send 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

Note

This method does not exist natively in csound 6, it just calls either inputMessage() or inputMessageAsync() respectively, depending on the value of the block param. It exists natively in csound 7 and was backported to csound 6 for forward compatibility

firstMessage()[source]#

Returns the first message from the buffer.

To keep reading the user needs to call Csound.popFirstMessage()

Return type:

str

Returns:

the first message in the buffer, or an empty string if there are no messages

See also

readMessage()

firstMessageAttr()[source]#

Returns the attribute parameter of the first message in the 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

getLibrarySymbol(library, symbolName)[source]#

Platform-independent function to get a symbol address in a shared library.

Note

Not present in csound 7

getOpcodes()[source]#

Get a list of all defined opcodes

This can be used instead of Csound.newOpcodeList() and Csound.disposeOpcodeList()

Return type:

list[OpcodeDef]

Returns:

a list of OpcodeDef, a dataclass with attributes namestr, outtypes: str, intypes: str, flags: int

hostData()[source]#

Returns host data.

Return type:

c_void_p

initTimerStruct(timerStruct)[source]#

Initializes a timer structure.

Note

not present in csound 7

inputBuffer()[source]#

Returns the Csound audio input buffer as an ndarray.

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

Note

Not present in csound 7. Use spin()

Return type:

ndarray

inputBufferSize()[source]#

Returns the number of samples in Csound’s input buffer.

Note

Not present in csound 7

Return type:

int

inputMessage(message)[source]#

Send a new event as a string, blocking

The syntax is the same as a score line

Note

use eventString() for compatibility with csound 7

Return type:

None

inputMessageAsync(message)[source]#

Asynchronous version of inputMessage()

See also

inputMessage()

Return type:

None

inputName()[source]#

Returns the audio input name (-i)

Note

this method is incompatible with csound 7

Return type:

str

isNamedGEN(num)[source]#

Checks if a given GEN number num is a named GEN.

Return type:

int

Returns:

the length of the gen’s name, or 0 if the gen does not exist

Note

not present in csound 7

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)

joinThread(thread)[source]#

Waits until the indicated thread’s routine has finished.

Returns the value returned by the thread routine.

Note

not present in csound 7

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()).

Return type:

None

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 can still be used both in csound 6 and csound 7, but in the latter it is implemented in csound code

kr()[source]#

Returns the number of control samples per second.

Return type:

float

ksmps()[source]#

Returns the number of audio sample frames per control sample.

Return type:

int

listChannels()[source]#

Returns a pointer and an error message.

The pointer points to a list of ControlChannelInfo objects for allocated channels. 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 pointer is None.

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

listUtilities()[source]#

Returns a list of registered utility names.

The return value may be None in case of an error.

Note

Not present in csound 7

Return type:

list[str]

loadPlugins(directory)[source]#

Loads all plugins from a given directory.

Parameters:

directory (str) – the path to the plugins directory

Return type:

int

lockMutex(mutex)[source]#

Acquires the indicated mutex object.

Parameters:

mutex (c_void_p) – the mutex, as returned by createMutex()

Return type:

None

If it is already in use by another thread, the function waits until the mutex is released by the other thread.

Note

not present in csound 7

lockMutexNoWait(mutex)[source]#

Acquire the indicated mutex object.

Parameters:

mutex (c_void_p) – the mutex, as returned by createMutex()

Return type:

int

Returns zero, unless it is already in use by another thread, in which case a non-zero value is returned immediately, rather than waiting until the mutex becomes available.

Note

this function may be unimplemented on Windows.

Note

not present in csound 7

message(fmt, *args)[source]#

Displays an informational message.

This is a workaround because ctypes does not support variadic functions. The arguments are formatted in a string, using the python way, either old style or new style, and then this formatted string is passed to the Csound display message system.

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, fmt, *args)[source]#

Prints message with special attributes.

(See msg_attr for the list of available attributes). With attr=0, messageS() is identical to message(). This is a workaround because ctypes does not support variadic functions. The arguments are formatted in a string, using the python way, either old style or new style, and then this formatted string is passed to the csound display message system.

Return type:

None

midiDevList(isOutput)[source]#

Returns a list of available input or output midi devices.

Parameters:

isOutput (bool) – if True, list output devices. Otherwise, list input devices

Return type:

list[MidiDevice]

Each item in the list is MidiDevice, with attributes deviceName (str), interfaceName (str), deviceId (str), midiModule (str), and isOutput (bool).

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) – the module number

Return type:

tuple[str, str, int]

Returns:

a tuple (name – str, type: str, errormsg: int), where name is the name of the module, type is one of “audio” or “midi” and errormsg is 0 if OK, CSOUND_ERROR if there is no module for the given number

n = 0
while True:
    name, type_, err = cs.module(n)
    if err == ctcsound.CSOUND_ERROR:
        break
    print("Module %d:%s (%s)\n" % (n, name, type_))
    n = n + 1

See also

Csound.modules()

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

Csound.module()

namedGEN(num, nameLen)[source]#

Gets the GEN name from a GEN number, if this is a named GEN.

The final parameter is the max len of the string.

Note

not present in csound 7

Return type:

str

namedGens()[source]#

Finds the list of named gens

Return type:

list[tuple[str, int]]

Returns:

a list of tuples of the form (name: str, num: int)

Note

not present in csound 7

nchnls()[source]#

Returns the number of audio output channels.

Set through the nchnls header variable in the csd file.

Return type:

int

nchnlsInput()[source]#

Returns the number of audio input channels.

Set through the nchnls_i header variable in the csd file. If this variable is not set, the value is taken from nchnls.

Return type:

int

newOpcodeList()[source]#

Gets an alphabetically sorted list of all opcodes.

Return type:

tuple[Array[OpcodeListEntry] | None, int]

Returns:

a tuple (entries – array[OpcodeListEntry], numentries: int)

Should be called after externals are loaded by compileCommandLine(). Returns a pointer to the list of OpcodeListEntry structures and the number of opcodes, or a negative error code on failure. Make sure to call disposeOpcodeList() when done with the list.

notifyThreadLock(lock)[source]#

Notifies the indicated monitor object.

Note

not present in csound 7

Return type:

None

openLibrary(libraryPath)[source]#

Platform-independent function to load a shared library.

Parameters:

libraryPath (str) – the path to the library

Return type:

tuple[int, c_void_p]

Returns:

a tuple (retcode – int, library: void)

Note

Not present in csound 7

outputBuffer()[source]#

Returns the Csound audio output buffer as an ndarray.

Return type:

ndarray

Returns:

a numpy array representing the csound audio output buffer

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

Note

Not present in csound 7. Use spout() instead

outputBufferSize()[source]#

Returns the number of samples in Csound’s output buffer.

Note

Not present in csound 7

Return type:

int

outputFormat()[source]#

Gets output type and format.

Return type:

tuple[str, str]

Returns:

a tuple (type – str, format: str)

Note

not compatible with csound 7

outputName()[source]#

Returns the audio output name (-o)

Note

This method is incompatible with csound 7

Return type:

str

params(params=None)[source]#

Gets the current set of parameters from a CSOUND instance.

Parameters:

params (CsoundParams | None) – if given, the passed instance is filled with the corresponding information, otherwise a new struct is created

Return type:

CsoundParams

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

p = CsoundParams()
cs.params(p)
parseOrc(orc)[source]#

Parses the given orchestra from string into a TREE.

This can be called during performance to parse new code.

Parameters:

orc (str) – the orchestra code to parse

Return type:

c_void_p

Returns:

a void pointer representing a TREE structure

Note

this method and the underlying functionality are not present in csound 7

peekCircularBuffer(circularBuffer, out, numitems)[source]#

Reads from circular buffer without removing them from the buffer.

Parameters:
  • buffer – pointer to an existing circular buffer

  • data – 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).

perform()[source]#

Handles input events and performs audio output.

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.

performBuffer()[source]#

Performs Csound, sensing real-time and score events.

Processing one buffer’s worth (-b frames) of interleaved audio.

Return type:

bool

Returns:

True if performance is finished, False otherwise

Note that compileCommandLine() must be called first, then call outputBuffer() and inputBuffer(()) to get ndarrays pointing to Csound’s I/O buffers.

Returns False during performance, and true when performance is finished.

Note

This method is not present in csound 7. Use performKsmps() for forward compatibility

performKsmps()[source]#

Handles input events, and performs audio output for one cycle

Return type:

bool

Returns:

True if performance is finished, False otherwise

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

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.

Returns False during performance, and 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.

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()

Calling the stop() method on the csound instance will also stop its attached thread, if created

popFirstMessage()[source]#

Removes the first message from the buffer.

Return type:

None

pvsChannel(fout, name)[source]#

Receives a PvsdatExt fout from the pvsout opcode (f-rate) at channel name.

Return type:

int

Returns:

zero on success, CSOUND_ERROR if the index is invalid or if fsig framesizes are incompatible; CSOUND_MEMORY if there is not enough memory to extend the bus.

queryGlobalVariable(name)[source]#

Gets pointer to space allocated with the name name.

Return type:

c_void_p | None

Returns:

an opaque pointer, or None if the variable is undefined

Note

Not implemented in csound 7

queryGlobalVariableNoCheck(name)[source]#

This function is the similar to :py:meth`queryGlobalVariable()`.

Except the variable is assumed to exist and no error checking is done. Faster, but may crash or return an invalid pointer if name is not defined.

Note

Not implemented in csound 7

Return type:

c_void_p

rand31(seed)[source]#

Simple linear congruential random number generator

seed = seed * 742938285 % 2147483647

The initial value of seed must be in the range 1 to 2147483646. Returns the next number from the pseudo-random sequence, in the range 1 to 2147483646.

Note

Not present in csound 7

Return type:

float

randMT(state)[source]#

Returns next random number from MT19937 generator.

Parameters:

state (CsoundRandMTState) – a CsoundRandMTState as returned by seedRandMT()

Return type:

float

The PRNG must be initialized first by calling :py:meth`seedRandMT()`.

Note

Not present in csound 7

randomSeedFromTime()[source]#

Returns a 32-bit unsigned integer to be used as seed from current time.

Note

not present in csound 7

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

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

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

readScore(sco)[source]#

Reads, preprocesses, and loads a score from a string

It can be called repeatedly, with the new score events being added to the currently scheduled ones.

Parameters:

sco (str) – the score text to read

Return type:

int

Returns:

CSOUND_SUCCESS on success, CSOUND_ERROR otherwise

readScoreAsync(sco)[source]#

Asynchronous version of readScore().

Return type:

None

realTime(timerStruct)[source]#

Returns the elapsed real time (in seconds).

The time is measured since the specified timer structure was initialised.

Note

not present in csound 7

Return type:

int

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).

registerSenseEventCallback(function, userData)[source]#

Registers a function to be called by sensevents().

This function will be called once in every control period. Any number of functions may be registered, and will be called in the order of registration.

The callback function takes two arguments: the Csound instance pointer, and the userData pointer as passed to this function.

This facility can be used to ensure a function is called synchronously before every csound control buffer processing. It is important to make sure no blocking operations are performed in the callback. The callbacks are cleared on cleanup().

Returns zero on success.

Note

this method has been removed in csound 7

removeKeyboardCallback(function)[source]#

Removes a callback previously set with registerKeyboardCallback().

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. Implies cleanup(), unless already called.

Return type:

None

rewindScore()[source]#

Rewinds a compiled Csound score.

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

Return type:

None

rtPlayUserData()[source]#

Returns pointer to user data pointer for real time audio output.

Note

Not present in csound 7

Return type:

c_void_p

rtRecordUserData()[source]#

Returns pointer to user data pointer for real time audio input.

Note

Not present in csound 7

Return type:

c_void_p

runCommand(args, noWait)[source]#

Runs an external command with the arguments specified in list args.

args[0] is the name of the program to execute (if not a full path file name, it is searched in the directories defined by the PATH environment variable).

If noWait is False, the function waits until the external program finishes, otherwise it returns immediately. In the first case, a non-negative return value is the exit status of the command (0 to 255), otherwise it is the PID of the newly created process. On error, a negative value is returned.

Note

not present in csound 7

runUtility(name, args)[source]#

Runs utility with the specified name and command line arguments.

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

scoreEvent(kind, pfields)[source]#

Sends a new score event (blocking)

Parameters:
  • kind (str) – score event type (‘a’, ‘i’, ‘q’, ‘f’, or ‘e’).

  • pfields (tuple[float, ...] | list[float] | ndarray) – a tuple, a list, or an ndarray of MYFLTs with all the pfields for this event, starting with p1

Return type:

int

Returns:

0 on success, an error code on failure

scoreEventAbsolute(kind, pfields, timeOffset=0.0)[source]#

Like scoreEvent(), this function inserts a score event.

Parameters:
  • kind (str) – score event type (‘a’, ‘i’, ‘q’, ‘f’, or ‘e’).

  • pfields (tuple[float, ...] | list[float] | ndarray) – a tuple, a list, or an ndarray of MYFLTs with all the pfields for this event, starting with p1

  • timeOffset (float) – the time offset to use as reference

Return type:

int

Returns:

0 on success, an error code otherwise

The event is inserted at absolute time with respect to the start of performance, or from an offset set with timeOffset.

Note

This method is not present in csound 7. Use

scoreEventAbsoluteAsync(type_, pfields, timeOffset=0.0)[source]#

Asynchronous version of scoreEventAbsolute().

Parameters:
  • kind – score event type (‘a’, ‘i’, ‘q’, ‘f’, or ‘e’).

  • pfields – a tuple, a list, or an ndarray of MYFLTs with all the pfields for this event, starting with p1

  • timeOffset (float) – the time offset to use as reference

Return type:

None

scoreEventAsync(kind, pfields)[source]#

Asynchronous version of scoreEvent().

Parameters:
  • kind (str) – score event type (‘a’, ‘i’, ‘q’, ‘f’, or ‘e’).

  • pfields (tuple[float, ...] | list[float] | ndarray) – a tuple, a list, or an ndarray of MYFLTs with all the pfields for this event, starting with p1

Return type:

None

scoreOffsetSeconds()[source]#

Returns the score time beginning midway through a Csound score.

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

Return type:

float

scoreTime()[source]#

Returns the current score time.

The return value is the time in seconds since the beginning of performance.

Return type:

float

seedRandMT(initKey)[source]#

Initializes Mersenne Twister (MT19937) random number generator.

Parameters:

initKey (Union[int, Sequence[int]]) – can be a single int, a list of int Those int values are converted to unsigned 32 bit values and used for seeding.

Return type:

CsoundRandMTState

Returns:

a CsoundRandMTState stuct to be used by – py:meth`csoundRandMT()`.

Note

Not present in csound 7

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

Return type:

None

See also

audioChannel()

setAudioDevListCallback(function)[source]#

Sets a callback for obtaining a list of audio devices.

This should be set by rtaudio modules and should not be set by hosts. (See audioDevList()).

setControlChannel(name, val)[source]#

Sets the value of control channel identified by name.

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

  • val (float) – the new value of the channel

Return type:

None

setControlChannelHints(name, hints)[source]#

Sets parameters hints for a control channel.

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

  • hints (ControlChannelHints) – the hints to set

Return type:

int

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.

setCscoreCallback(function)[source]#

Sets an external callback for Cscore processing.

Pass None to reset to the internal cscore() function (which does nothing). This callback is retained after a reset() call.

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.

setEndMarker(time)[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

Return type:

None

Example

import libcsound
csound = libcsound.Csound()
csound.setOption('-ooutfile.wav')
csound.compileOrc(r'''

sr = 44100
ksmps = 64
nchnls = 2
0dbfs = 1

instr 1
  kchan init -1
  kchan = (kchan + metro:k(1)) % nchnls
  if changed:k(kchan) == 1 then
    println "Channel: %d", kchan + 1
  endif
  asig = pinker() * 0.2
  outch kchan + 1, asig
endin

''')
csound.start()
csound.scoreEvent("i", [1, 0, 10])
csound.setEndMarker(10)
# Perform until the end of the score
# Without the end marker this would render for ever
while not csound.performKsmps():
    pass
setExitGraphCallback(function)[source]#

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

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.

Return type:

None

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.

Return type:

None

setExternalMidiOutOpenCallback(function)[source]#

Sets a callback for opening real-time Midi input.

Return type:

None

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.

Return type:

None

setFileOpenCallback(function)[source]#

Sets a callback for receiving notices whenever Csound opens a file.

Parameters:

function (Callable[[bytes, int, int, int], None]) – the callback

Return type:

None

The callback is made after the file is successfully opened. The following information is passed to the callback:

bytes

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

int

a file type code from the enumeration CSOUND_FILETYPES

int

1 if Csound is writing the file, 0 if reading

int

1 if a temporary file that Csound will delete; 0 if not

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

setGlobalEnv(name, value)[source]#

Sets the global value of environment variable name to value.

Parameters:
  • name (str) – variable name

  • value (str | None) – variable value. The key: value pair is deleted if the value is None

Returns:

zero on success, an error code otherwise

Note

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

setHostData(data)[source]#

Sets host data.

Parameters:

data – can be any data

Return type:

None

setHostImplementedAudioIO(state, bufSize=0)[source]#

Sets user handling of sound I/O.

Parameters:
  • state (bool) – if True, will disable all default handling of sound IO

  • bufSize (int) – buffer size

Calling this function with a True state value between creation of the Csound object and the start of performance will disable all default handling of sound I/O by the Csound library, allowing the host application to use the spin/spout/input/output buffers directly.

For applications using spin/spout, bufSize should be set to 0. If bufSize is greater than zero, the buffer size (-b) will be set to the integer multiple of ksmps() that is nearest to the value specified.

Note

This method changed its name in csound 7 to setHostAudioIO

setHostImplementedMidiIO(state)[source]#

Called with state True if the host is implementing via callbacks.

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 API function which is used by this method (csoundSetInput) does not exist in csound 7. The method itself has been implemented in csound 7 using command-line options (-i option) and can be safely used for future compatibility

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.

setLanguage(langcode)[source]#

Sets language to langcode.

langcode can be for example CSLANGUAGE_ENGLISH_UK or CSLANGUAGE_FRENCH or many others, (see n_getstr.h for the list of languages). This affects all Csound instances running in the address space of the current process. The special language code CSLANGUAGE_DEFAULT can be used to disable translation of messages and free all memory allocated by a previous call to setLanguage(). setLanguage() loads all files for the selected language from the directory specified by the CSSTRNGS environment variable.

Note

not present in csound 7

setMakeGraphCallback(function)[source]#

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

setMessageLevel(messageLevel)[source]#

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

Return type:

None

setMidiDevListCallback(function)[source]#

Sets a callback for obtaining a list of Midi devices.

This should be set by IO plugins and should not be set by hosts. (See midiDevList()).

setMidiFileInput(name)[source]#

Sets Midi file input name.

Parameters:

name (str) – the path to the Midi file used as input

Return type:

None

setMidiFileOutput(name)[source]#

Sets Midi file output name.

Parameters:

name (str) – name of a Midi file to output to.

Return type:

None

setMidiInput(name)[source]#

Sets Midi input device name/number.

Parameters:

name (str) – name of the input midi device

Return type:

None

Note

The API function which is used by this method (csoundSetMIDIInput) does not exist in csound 7. The method itself has been implemented in csound 7 using command-line options (-i option) and can be safely used for future compatibility (see :meth:`libcsound.api7.Csound.setMidiInput’)

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

setMidiOutput(name)[source]#

Sets Midi output device name/number.

Parameters:

name (str) – Midi device to use as output

Return type:

None

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:

CSOUND_SUCCESS on success.

This needs to be called before any code is compiled. Multiple options are allowed in one string. Returns zero on success.

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

See csound --help for a complete list of options

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

Sets output destination, type and format.

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

  • filetype – 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

The API function which is used by this method (csoundSetOutput) does not exist in csound 7. The method itself has been implemented in csound 7 using command-line options (--format=...) and can be safely used for future compatibility

setOutputChannelCallback(function)[source]#

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

setParams(params)[source]#

Configures Csound with a given set of parameters.

Parameters:

params (CsoundParams) – an instance of CsoundParams

Return type:

None

Note

This method is NOT compatible with csound 7. In csound 7 it does not exist. All parameters can be set via command line arguments

These parameters are defined in the CsoundParams structure. They are the part of the OPARMS struct that are configurable through command line flags. The CsoundParams structure can be obtained using params(). These options should only be changed before performance has started.

setPlayOpenCallback(function)[source]#

Sets a callback for opening real-time audio playback.

Parameters:

function (Callable) – a function of the form (void, CsoundRtAudioParams*) -> int

Return type:

None

Note

not implemented in csound 7

setPvsChannel(fin, name)[source]#

Sends a PvsdatExt fin to the pvsin opcode (f-rate) for channel name.

Parameters:
  • fin (PvsdatExt) – the pvs data

  • name (str) – name of the channel

Return type:

int

Returns:

zero on success, CSOUND_ERROR if the index is invalid or fsig framesizes are incompatible.or CSOUND_MEMORY if there is not enough memory to extend the bus.

setRTAudioModule(module)[source]#

Sets the current RT audio module.

Parameters:

module (str) – the name of the module.

Platform

Modules

linux

jack, pa_cb (portaudio)

macos

au_hal (coreaudio), pa_cb, jack

windows

pa_cb (portaudio), winmm

Return type:

None

setRecordOpenCallback(function)[source]#

Sets a callback for opening real-time audio recording.

Note

not implemented in csound 7

Return type:

None

setRtCloseCallback(function)[source]#

Sets a callback for closing real-time audio playback and recording.

Note

not implemented in csound 7

setRtPlayCallback(function)[source]#

Sets a callback for performing real-time audio playback.

Note

not implemented in csound 7

Return type:

None

setRtRecordCallback(function)[source]#

Sets a callback for performing real-time audio recording.

Note

not implemented in csound 7

Return type:

None

setScoreOffsetSeconds(time)[source]#

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

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.

Return type:

None

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

setSpinSample(frame, channel, sample)[source]#

Sets the audio input working buffer (spin) to the indicated sample.

This only ever makes sense before calling performKsmps(). The frame and channel must be in bounds relative to ksmps() and nchnlsInput().

Parameters:
  • frame (int) – frame number

  • channel (int) – channel number

  • sample (float) – sample value

Note

Not present in csound 7

setStringChannel(name, string)[source]#

Sets the string channel identified by name with string.

Return type:

None

setYieldCallback(function)[source]#

Called by external software to set a yield function.

This callback is used for checking system events, yielding cpu time for coopertative multitasking, etc.

This function is optional. It is often used as a way to ‘turn off’ Csound, allowing it to exit gracefully. In addition, some operations like utility analysis routines are not reentrant and you should use this function to do any kind of updating during the operation.

Returns an ‘OK to continue’ boolean.

Note

not present in csound 7

sizeOfMYFLT()[source]#

Returns the size of MYFLT in bytes.

Return type:

int

sleep(milliseconds)[source]#

Waits for at least the specified number of milliseconds.

Parameters:

milliseconds (int) – time to sleep, in milliseconds

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 performKsmps().

Return type:

ndarray

spinLock(spinlock)[source]#

Locks the spinlock.

Note

not present in csound 7

Return type:

None

spinLockInit(spinlock)[source]#

Inits the spinlock.

Parameters:

spinlock (c_int | None) – if given, initializes the given spinlock. Otherwise a new spinlock is created

Return type:

c_int

Returns:

the initialized spinlock

If the spinlock is not locked, locks it and returns; if is is locked, waits until it is unlocked, then locks it and returns. Uses atomic compare and swap operations that are safe across processors and safe for out of order operations, and which are more efficient than operating system locks.

Use spinlocks to protect access to shared data, especially in functions that do little more than read or write such data, for example:

lock = ctypes.ct.c_int32(0)
cs.spinLockInit(lock)
def write(cs, frames, signal):
    cs.spinLock(lock)
    for frame in range(frames) :
        global_buffer[frame] += signal[frame];
    cs.spinUnlock(lock)

Note

not present in csound 7

spinTryLock(spinlock)[source]#

Tries the spinlock.

returns CSOUND_SUCCESS if lock could be acquired, CSOUND_ERROR, otherwise.

Note

not present in csound 7

Return type:

int

spinUnlock(spinlock)[source]#

Unlocks the spinlock.

Note

not present in csound 7

Return type:

None

spout()[source]#

Returns the address of the Csound audio output working buffer (spout).

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

Return type:

ndarray

spoutSample(frame, channel)[source]#

Returns one sample from the Csound audio output working buf (spout).

Only ever makes sense after calling performKsmps(). The frame and channel must be in bounds relative to ksmps() and nchnls().

Note

Not present in csound 7. Use spout()

Return type:

float

sr()[source]#

Returns the number of audio sample frames per second.

Return type:

float

start()[source]#

Prepares Csound for performance.

Return type:

int

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 a csd file or an orc file, score preprocessing is not performed and “i” statements are dispatched as real-time events. In this case, any options given as part of a <CsOptions> tag 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]#

Stops a perform() running in another thread.

Note that it is not guaranteed that perform() has already stopped when this function returns.

Return type:

None

stopUDPConsole()[source]#

Stops transmitting console messages via UDP.

Note

This method is not present in csound 7

Return type:

None

stringChannel(name)[source]#

Get a string from the given channel

Parameters:

name (str) – the name of the channel. It must be already created and be of string type

Return type:

str

Returns:

the string value of the channel

systemSr(val=0)[source]#

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

Parameters:

val (int) – 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 as an ndarray.

Return type:

ndarray | None

Returns:

a numpy array pointing to the actual data, or None if the table does not exist. The ndarray does not include the guard point.

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

tableCopyIn(table, src)[source]#

Copies the contents of an ndarray src into a given function table.

The table number is assumed to be valid, and the table needs to have sufficient space to receive all the array contents.

Note

not present in csound 7. Use table() instead

tableCopyInAsync(table, src)[source]#

Asynchronous version of tableCopyIn().

Note

not present in csound 7. Use table() instead

tableCopyOut(table, dest)[source]#

Copies the contents of a function table into a supplied ndarray dest.

Parameters:
  • table (int) – table number

  • dest (ndarray) – where to put the contents of the table (needs to have enough space)

Return type:

None

Note

not present in csound 7. Use table() instead

tableCopyOutAsync(table, dest)[source]#

Asynchronous version of tableCopyOut().

Note

not present in csound 7. Use table() instead

tableGet(table, index)[source]#

Returns the value of a slot in a function table.

Parameters:
  • table (int) – table number

  • index (int) – index within the table

Return type:

float

Returns:

the value of the table at the given index

The table number and index are assumed to be valid.

Note

This method is not present in csound 7. Use table() directly

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

tableSet(table, index, value)[source]#

Sets the value of a slot in a function table.

The table number and index are assumed to be valid.

Note

This method is not present in csound 7. Use table() directly

Return type:

None

unlockMutex(mutex)[source]#

Releases the indicated mutex object.

Parameters:

mutex (c_void_p) – the mutex, as returned by createMutex()

Return type:

None

The mutex should be owned by the current thread, otherwise the operation of this function is undefined. A recursive mutex needs to be unlocked as many times as it was locked previously.

Note

not present in csound 7

utilityDescription(name)[source]#

Gets utility description.

Returns an empty string if the utility was not found, or it has no description, or an error occured.

Note

Not present in csound 7

Return type:

str

version()[source]#

Returns the version number x 1000 (6.18.0 = 6180).

Return type:

int

Returns:

an int representing the version

waitBarrier(barrier)[source]#

Waits on the thread barrier.

Parameters:

barrier (c_void_p) – the barrier, as returned by Csound.createBarrier()

Note

not present in csound 7

waitThreadLock(lock, milliseconds)[source]#

Waits on the indicated monitor object for the indicated period.

The function returns either when the monitor object is notified, or when the period has elapsed, whichever is sooner; in the first case, zero is returned.

If milliseconds is zero and the object is not notified, the function will return immediately with a non-zero status.

Note

not present in csound 7

Return type:

int

waitThreadLockNoTimeout(lock)[source]#

Waits on the indicated monitor object until it is notified.

This function is similar to waitThreadLock() with an infinite wait time, but may be more efficient.

Note

not present in csound 7

Return type:

None

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

Returns:

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

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

Performs a score in a separate thread until the end of score is reached.

The playback (which is paused by default) is stopped by calling stop(), or if an error occurs. The constructor takes a Csound instance as argument. Once the playback is stopped for one of the above mentioned reasons, the performance thread calls Csound.cleanup and returns.

Parameters:

csound (Csound) – the Csound object (not the bare pointer)

Example

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

From the user perspective the recommended way to create a performance thread is to call the performanceThread() method:

perfthread = cs.performanceThread()

Attributes:

cpt

The opaque pointer to the actual CsoundPerformanceThread

csound

The Csound instance corresponding to this PerformanceThread

Methods:

csoundPtr()

Returns the Csound instance pointer.

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

isRunning()

Returns 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.

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 process 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.

cpt#

The opaque pointer to the actual CsoundPerformanceThread

csound#

The Csound instance corresponding to this PerformanceThread

csoundPtr()[source]#

Returns the Csound instance pointer.

Return type:

c_void_p

flushMessageQueue()[source]#

Waits until all pending messages are actually received.

(pause, send score event, etc.)

Return type:

None

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

Parameters:

s (str) – a string representing a line within a score (following the score syntax)

Return type:

None

isRunning()[source]#

Returns 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:

a positive value if the end of score was reached or stop() was called, and a negative value 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.

Return type:

None

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], None]) – a function of the form (csound: Csound) -> None, which can access the csound API

Return type:

None

Note

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

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

compile(), evalCode()

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

Starts recording the output from Csound.

Args:

filename: the output soundfile. Format is always WAVE samplebits: number of bits per sample (16, 24, 32) numbufs: number of buffers

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

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

Sends a score event.

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

  • 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:

None

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 process tasks within the performance loop

Note

This sets up the process callback.

Return type:

None

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.

Return type:

int

Returns:

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

stop()[source]#

Stops performance (cannot be continued).

Return type:

None

stopRecord()[source]#

Stops recording and closes audio file.

Return type:

None

togglePause()[source]#

Pauses or continues performance, depending on current state.

Return type:

None