Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/csound/csound/llms.txt

Use this file to discover all available pages before exploring further.

The ctcsound module provides Python bindings to the Csound C API using Python’s ctypes library.

Module initialization

csound_initialize
function
Initialize the Csound library with specific flags.
result = ctcsound.csound_initialize(flags)
Parameters:
  • flags (int) - Initialization flags:
    • CSOUNDINIT_NO_SIGNAL_HANDLER = 1
    • CSOUNDINIT_NO_ATEXIT = 2
Returns: Zero on success, positive if already initialized, negative on error.
This function is called automatically by Csound() constructor. You rarely need to call it explicitly.

Csound class

The main class for interacting with Csound.

Constructor

cs = ctcsound.Csound(host_data=None, opcode_dir=None, pointer_=None)
Parameters:
  • host_data - Optional data accessible from callbacks
  • opcode_dir - Optional override for plugin directory search
  • pointer_ - Optional existing Csound pointer (advanced use)

Attributes and properties

version
method
Get Csound version number.
version = cs.version()
# Returns: 7000 for version 7.0.0
sr
method
Get sample rate (audio frames per second).
sample_rate = cs.sr()
# Returns: float (e.g., 44100.0)
kr
method
Get control rate (control samples per second).
control_rate = cs.kr()
# Returns: float (e.g., 4410.0)
ksmps
method
Get audio vector size in frames (sr/kr).
vector_size = cs.ksmps()
# Returns: int (e.g., 64)
channels
method
Get number of audio channels.
num_channels = cs.channels(is_input=False)
Parameters:
  • is_input (bool) - If True, returns nchnls_i, otherwise nchnls
get_0dBFS
method
Get 0dBFS level of audio buffers.
zero_db = cs.get_0dBFS()
# Returns: float (typically 1.0)
A4
method
Get A4 frequency reference.
a4_freq = cs.A4()
# Returns: float (typically 440.0)
current_time_samples
method
Get current performance time in sample frames.
samples = cs.current_time_samples()
# Returns: int
size_of_MYFLT
method
Get size of MYFLT type in bytes.
size = cs.size_of_MYFLT()
# Returns: int (typically 8 for double)

Configuration

set_option
method
Set Csound command-line options.
result = cs.set_option("-odac")
Must be called before compilation. Multiple options can be in one string.Returns: Zero on success.
params
method
Get current parameters into a CsoundParams structure.
params = ctcsound.CsoundParams()
cs.params(params)
print(params.sr_override)
set_debug
method
Enable or disable debug messages.
cs.set_debug(True)
set_message_level
method
Set message level (0-231).
cs.set_message_level(0)  # No messages

Performance

compile_
method
Compile Csound input files.
result = cs.compile_("myfile.csd")
# Or with multiple arguments:
result = cs.compile_("csound", "-odac", "myfile.csd")
Returns: Non-zero on error.
compile_orc
method
Compile orchestra code from a string.
orc = '''
sr = 44100
ksmps = 64
instr 1
  out oscili(0.5, 440)
endin
'''
result = cs.compile_orc(orc, async_=False)
Parameters:
  • orc (str) - Orchestra code
  • async_ (bool) - If True, compile asynchronously
eval_code
method
Evaluate code and return a value.
code = 'i1 = 2 + 2\nreturn i1'
result = cs.eval_code(code)
# Returns: 4.0
compile_csd
method
Compile a CSD file or string.
# From file:
cs.compile_csd("myfile.csd", mode=0, async_=False)

# From string:
csd_text = "<CsoundSynthesizer>...</CsoundSynthesizer>"
cs.compile_csd(csd_text, mode=1, async_=False)
Parameters:
  • csd (str) - Filename or CSD text
  • mode (int) - 0 for file, 1 for text string
  • async_ (bool) - If True, compile asynchronously
start
method
Prepare Csound for performance.
result = cs.start()
Returns: Non-zero on error.
perform_ksmps
method
Process one control period (ksmps samples).
while cs.perform_ksmps() == 0:
    # Process audio...
    pass
Returns: False during performance, True when finished.
reset
method
Reset Csound for a new performance.
cs.reset()
Clears all internal memory and state.
run_utility
method
Run a Csound utility.
result = cs.run_utility("sndinfo", ["soundfile.wav"])
Call reset() after using utilities.

Audio I/O

spin
method
Get audio input buffer as NumPy array.
import numpy as np

input_buffer = cs.spin()
# Shape: (ksmps * nchnls_i,)
Write to this buffer before calling perform_ksmps().
spout
method
Get audio output buffer as NumPy array.
output_buffer = cs.spout()
# Shape: (ksmps * nchnls,)
Read from this buffer after calling perform_ksmps().
set_host_audio_IO
method
Disable default audio I/O handling.
cs.set_host_audio_IO()
Use spin() and spout() buffers directly after calling this.
set_RT_audio_module
method
Set the real-time audio module.
cs.set_RT_audio_module("portaudio")

Channels

set_control_channel
method
Set a control channel value.
cs.set_control_channel("frequency", 440.0)
control_channel
method
Get a control channel value.
value, err = cs.control_channel("frequency")
if err is None:
    print(f"Frequency: {value}")
set_audio_channel
method
Set an audio channel from NumPy array.
import numpy as np

samples = np.zeros(cs.ksmps(), dtype=ctcsound.MYFLT)
cs.set_audio_channel("audioIn", samples)
audio_channel
method
Get an audio channel into NumPy array.
samples = np.zeros(cs.ksmps(), dtype=ctcsound.MYFLT)
cs.audio_channel("audioOut", samples)
set_string_channel
method
Set a string channel.
cs.set_string_channel("filename", "sample.wav")
string_channel
method
Get a string channel value.
filename = cs.string_channel("filename")
channel_ptr
method
Get a pointer to a channel.
ptr, err = cs.channel_ptr("myChannel", 
    ctcsound.CSOUND_CONTROL_CHANNEL | ctcsound.CSOUND_INPUT_CHANNEL)

if err == "":
    # Use pointer...
    pass
Returns a NumPy array for control/audio channels.
list_channels
method
List all allocated channels.
channels, err = cs.list_channels()
if channels:
    for i in range(len(channels)):
        info = channels[i]
        print(f"{info.name}: {info.type}")
    cs.delete_channel_list(channels)
lock_channel
method
Lock a channel for thread-safe access.
cs.lock_channel("myChannel")
# Access channel data...
cs.unlock_channel("myChannel")

Events

event
method
Send a score event.
import numpy as np

# Note event: i1 0 1 440
params = np.array([1, 0, 1, 440], dtype=ctcsound.MYFLT)
cs.event(ctcsound.CS_INSTR_EVENT, params, async_=False)
event_string
method
Send score event(s) as a string.
cs.event_string("i 1 0 1 440", async_=False)

# Multiple events:
cs.event_string("i 1 0 1 440\ni 1 1 1 550", async_=False)
instr_number
method
Get instrument number from name.
num = cs.instr_number("MyInstrument")
# Returns: int or -1 if not found

Tables

table
method
Get function table as NumPy array.
table_data = cs.table(1)
if table_data is not None:
    print(f"Table 1 length: {len(table_data)}")
table_length
method
Get function table length.
length = cs.table_length(1)
# Returns: -1 if table doesn't exist
tableArgs
method
Get GEN arguments for a table.
args = cs.tableArgs(1)
if args is not None:
    print(f"GEN number: {args[0]}")

Messages

message
method
Display an informational message.
cs.message("Frequency: {}", 440.0)
# Or old-style:
cs.message("Frequency: %f", 440.0)
create_message_buffer
method
Create a message buffer.
cs.create_message_buffer(to_stdout=True)

# Later, read messages:
while cs.message_cnt() > 0:
    msg = cs.first_message()
    attr = cs.first_message_attr()
    print(msg)
    cs.pop_first_message()

cs.destroy_message_buffer()

Device enumeration

audio_dev_list
method
Get list of audio devices.
devices = cs.audio_dev_list(is_output=True)
for dev in devices:
    print(f"{dev['device_name']}: {dev['max_nchnls']} channels")
midi_dev_list
method
Get list of MIDI devices.
devices = cs.midi_dev_list(is_output=False)
for dev in devices:
    print(f"{dev['device_name']} ({dev['midi_module']})")

Score handling

score_time
method
Get current score time in seconds.
time = cs.score_time()
is_score_pending
method
Check if score events are being performed.
pending = cs.is_score_pending()
set_score_pending
method
Enable/disable score event performance.
cs.set_score_pending(False)  # Mute score
rewind_score
method
Rewind score to beginning.
cs.rewind_score()

CsoundPerformanceThread class

Runs Csound in a separate thread.

Constructor

pt = ctcsound.CsoundPerformanceThread(csound_pointer)
Parameters:
  • csound_pointer - Pointer from cs.csound()

Methods

play
method
Start or continue performance.
pt.play()
pause
method
Pause performance.
pt.pause()
toggle_pause
method
Toggle pause state.
pt.toggle_pause()
stop
method
Stop performance (cannot be continued).
pt.stop()
is_running
method
Check if thread is running.
if pt.is_running():
    print("Still playing...")
status
method
Get performance status.
status = pt.status()
# 0 = playing, positive = ended, negative = error
join
method
Wait for performance to finish.
result = pt.join()
# Returns: positive if ended normally, negative on error
score_event
method
Send a score event from the thread.
import numpy as np

pfields = np.array([1, 0, 1, 440], dtype=ctcsound.MYFLT)
pt.score_event(absp2mode=0, opcod='i', pFields=pfields)
input_message
method
Send score event string.
pt.input_message("i 1 0 1 440")
record
method
Start recording output to file.
pt.record("output.wav", samplebits=16, numbufs=4)
stop_record
method
Stop recording.
pt.stop_record()

Data structures

CsoundParams

Configuration parameters structure with fields:
  • debug_mode (int) - Debug flag
  • sr_override (MYFLT) - Sample rate override
  • kr_override (MYFLT) - Control rate override
  • ksmps_override (int) - ksmps override
  • nchnls_override (int) - Number of channels override
  • message_level (int) - Message level (0-231)
  • number_of_threads (int) - Thread count for multicore
  • And many more configuration fields…

ControlChannelHints

Hints for control channel GUI display:
hints = ctcsound.ControlChannelHints()
hints.behav = ctcsound.CSOUND_CONTROL_CHANNEL_LIN
hints.dflt = 440.0
hints.min = 20.0
hints.max = 20000.0
hints.attributes = None

cs.set_control_channel_hints("frequency", hints)

CsoundAudioDevice

Audio device information:
  • device_name (str) - Device name
  • device_id (str) - Device ID
  • rt_module (str) - RT module name
  • max_nchnls (int) - Maximum channels
  • isOutput (int) - 1 if output device

CsoundMidiDevice

MIDI device information:
  • device_name (str) - Device name
  • interface_name (str) - Interface name
  • device_id (str) - Device ID
  • midi_module (str) - MIDI module name
  • isOutput (int) - 1 if output device

Utility functions

cstring
function
Convert Python string to C string.
c_str = ctcsound.cstring("hello")
pstring
function
Convert C string to Python string.
py_str = ctcsound.pstring(c_str)
cchar
function
Convert Python string to C char.
c_ch = ctcsound.cchar('i')

Build docs developers (and LLMs) love