csoundlib - Utilities to work with csound#

csoundengine.csoundlib Module#

This module provides miscellaneous functionality for working with csound.

This functionality includes:

  • parse csound code

  • generate a .csd file

  • inspect the audio environment

  • query different paths used by csound

  • etc.

Functions#

audioBackends([available, platform])

Return a list of audio backends for the given platform

bestSampleEncodingForExtension(ext)

Given an extension, return the best sample encoding.

channelTypeFromValue(value)

Channel type (k, S, a) from value

compressionBitrateToQuality(bitrate[, fmt])

Convert a bitrate to a compression quality between 0-1, as passed to --vbr-quality

compressionQualityToBitrate(quality[, fmt])

Convert compression quality to bitrate

csoundOptionForSampleEncoding(encoding)

Returns the command-line option for the given sample encoding.

csoundOptionsForOutputFormat([fmt, encoding])

Returns the command-line options for the given format+encoding

csoundSubproc(args[, piped, wait])

Calls csound with given args in a subprocess, returns a subprocess.Popen object.

dumpAudioBackends()

Prints all available backends and their properties as a table

dumpAudioDevices([backend])

Print a list of audio devices for the given backend.

dumpAudioInfo([backend])

Dump information about audio backends and audio devices for the selected backend

fillPfields(args, namedpargs, defaults)

ftsaveRead(path[, mode])

Read a file saved by ftsave, returns a list of tables

getAudioBackend([name])

Given the name of the backend, return the AudioBackend structure

getAudioBackendNames([available, platform])

Returns a list with the names of the audio backends for a given platform

getAudioDevices(backend)

Returns (indevices, outdevices), where each of these lists is an AudioDevice.

getDefaultAudioDevices([backend])

Returns the default audio devices for a given backend

getDefaultBackend()

Get the default active backend for platform

getNchnls([backend, outpattern, inpattern, ...])

Get the default number of channels for a given device

getSamplerateForBackend([backend])

Returns the samplerate reported by the given backend

getSystemSr(backend)

Get the system samplerate for a given backend

getVersion([useApi])

Returns the csound version as tuple (major, minor, patch)

highlightCsoundOrc(code[, theme])

Converts csound code to html with syntax highlighting

installedOpcodes([cached, opcodedir])

Return a list of the opcodes present

instrGetBody(textOrLines)

instrNames(instrdef)

Returns the list of names/instrument numbers in the instrument definition.

instrParseBody(body)

Parses the body of an instrument, returns pfields used, output channels, etc.

isPfield(name)

Is name a pfield?

joinCsd(orc[, sco, options])

Joins an orc and a score (both as str), returns a csd as string

lastAssignmentToVariable(varname, lines)

Line of the last assignment to a variable

locateDocstring(lines)

Locate the docstring in this instr code

makeIncludeLine(include)

Given a path, creates the #include directive

midiDevices([backend])

Returns input and output midi devices for the given backend

mincer(sndfile, outfile, timecurve, pitchcurve)

Stretch/Pitchshift a output using csound's mincer opcode (offline)

nextpow2(n)

Returns the power of 2 higher or equal than n

normalizeInstrumentName(name)

Transform name so that it can be accepted as an instrument name

normalizeNamedPfields(pfields[, namesToIndexes])

Given a dict mapping pfield as str to value, return a dict mapping pfield index to value

parseOrc(code[, keepComments])

Parse orchestra code into blocks

recInstr(body, events[, init, outfile, sr, ...])

Record one instrument for a given duration

runCsd(csdfile[, outdev, indev, backend, ...])

Run the given .csd as a csound subprocess

saveAsGen23(data, outfile[, fmt, header])

Saves the data to a gen23 table

saveMatrixAsGen23(outfile, mtx[, extradata, ...])

Save a numpy 2D array as gen23

saveMatrixAsMtx(outfile, data[, metadata, ...])

Save data in wav format using the mtx extension

soundfontIndex(sfpath)

Make a SoundFontIndex for the given soundfont

soundfontInstrument(sfpath, name)

Get the instrument number from a preset

soundfontInstruments(sfpath)

Get instruments for a soundfont

soundfontKeyrange(sfpath, preset)

soundfontPeak(sfpath, preset[, pitches, dur])

soundfontPresets(sfpath)

Get presets from a soundfont

soundfontSelectPreset(sfpath)

Select a preset from a soundfont interactively

splitDocstring(body)

splitInclude(line)

Given an include line it splits the include path

splitScoreLine(line[, quote])

testCsound([dur, nchnls, backend, device, ...])

Test the current csound installation for realtime output

userPluginsFolder([float64, apiversion])

Returns the user plugins folder for this platform

Classes#

Any(*args, **kwargs)

Special type indicating an unconstrained type.

AudioBackend(name[, alwaysAvailable, ...])

Holds information about a csound audio backend

AudioDevice(id, name, kind[, index, ...])

An AudioDevice holds information about a an audio device for a given backend

CsoundProc(proc, backend, outdev, sr, nchnls)

A CsoundProc wraps a running csound subprocess

MidiDevice(deviceid, name[, kind])

A MidiDevice holds information about a midi device for a given backend

ParsedBlock(kind, lines, startLine[, ...])

A ParsedBlock represents a block (an instr, an opcode, etc) in an orchestra

ParsedInstrBody(pfieldIndexToName, ...[, ...])

The result of parsing the body of an instrument

RenderJob(outfile, samplerate[, encoding, ...])

Represent an offline render process

SoundFontIndex(soundfont)

Creates an index of presets for a given soundfont

runonce(func)

To be used as decorator.

class csoundengine.csd.Csd(sr=44100, ksmps=64, nchnls=2, a4=442.0, options=None, nodisplay=False, carry=False, nchnls_i=None, numthreads=0, reservedTables=0)[source]#

Build a csound script by adding global code, instruments, score events, etc.

Parameters:
  • sr (int) – the sample rate of the generated audio

  • ksmps (int) – the samples per cycle to use

  • nchnls (int) – the number of output channels

  • nchnls_i (int | None) – if given, the number of input channels

  • a4 (float) – the reference frequency

  • options (list[str] | None) – any number of command-line options passed to csound

  • nodisplay – if True, avoid outputting debug information

  • carry – should carry be enabled in the score?

  • reservedTables (int) – when creating tables, table numbers are autoassigned from python. There can be conflicts of any code uses ftgen

Example

>>> from csoundengine.csd import Csd
>>> csd = Csd(ksmps=32, nchnls=4)
>>> csd.addInstr('sine', r'''
...   ifreq = p4
...   outch 1, oscili:a(0.1, ifreq)
... ''')
>>> source = csd.addSndfile("sounds/sound1.wav")
>>> csd.playTable(source)
>>> csd.addEvent('sine', 0, 2, [1000])
>>> csd.write('out.csd')

Attributes:

score

The score, a list of ScoreLine

instrs

The orchestra

opcodes

User defined opcodes

globalcodes

Code to evaluate at the instr0 level

options

Command line options

ksmps

Samples per cycle

nchnls

Number of output channels

nchnls_i

Number of input channels

a4

Reference frequency

nodisplay

Disable display opcodes

enableCarry

Enable carry in the score

numthreads

Number of threads used for rendering

datafiles

Maps assigned table numbers to their metadata

sr

Samplerate

Methods:

copy()

Copy this csd

cropScore([start, end])

Crop the score at the given boundaries

dumpScore()

Show the score as a table

addScoreLine(line[, comment])

Add a score line verbatim

addEvent(instr, start, dur[, args, comment, ...])

Add an instrument ("i") event to the score

strset(s, index)

Add a strset to this csd

addTableFromData(data[, tabnum, start, ...])

Add a table definition with the data

addEmptyTable(size[, tabnum, sr, ...])

Add an empty table to this Csd

freeTable(tabnum, time)

Free a table

addSndfile(sndfile[, tabnum, start, ...])

Add a table which will load this sndfile

destroyTable(tabnum, time)

Schedule ftable with index source to be destroyed at time time

setEndMarker(time)

Add an end marker to the score

removeEndMarker()

Remove the end-of-score marker

setComment(comment)

Add a comment to the renderer output soundfile

setOutfileFormat(fmt)

Sets the format for the output soundfile

setSampleEncoding(encoding)

Set the sample encoding for recording

setCompressionQuality([quality])

Set the compression quality

setCompressionBitrate([bitrate, format])

Set the compression quality by defining a bitrate

scoreDuration()

Returns the duration of this score

addInstr(instr, body[, instrComment, extranames])

Add an instrument definition to this csd

addOpcode(name, outargs, inargs, body)

Add an opcode to this csd

addGlobalCode(code[, acceptDuplicates])

Add code to the instr 0

addOptions(*options)

Adds options to this csd

dump()

Returns a string with the .csd

playTable(tabnum, start[, dur, gain, speed, ...])

Add an event to play the given table

write(csdfile)

Write this as a .csd

render([outfile, verbose])

Render this csd offline

run(output[, csdfile, inputdev, backend, ...])

Run this csd.

setPfield(p1, pindex, value, start)

Set the value of a pfield for a scheduled event

automatePfield(p1, pindex, pairs, start)

Automate the pfield of a scheduled event

score: list[ScoreLine]#

The score, a list of ScoreLine

instrs: dict[str | int, _InstrDef]#

The orchestra

opcodes: dict[str, _OpcodeDef]#

User defined opcodes

globalcodes: list[str]#

Code to evaluate at the instr0 level

options: list[str]#

Command line options

ksmps#

Samples per cycle

nchnls#

Number of output channels

nchnls_i#

Number of input channels

a4#

Reference frequency

nodisplay#

Disable display opcodes

enableCarry#

Enable carry in the score

numthreads#

Number of threads used for rendering

datafiles: dict[int, _TableDataFile]#

Maps assigned table numbers to their metadata

property sr: int#

Samplerate

copy()[source]#

Copy this csd

Return type:

Csd

cropScore(start=0.0, end=0.0)[source]#

Crop the score at the given boundaries

Any event starting earlier or ending after the given times will be cropped, any event ending before start or starting before end will be removed

Return type:

None

dumpScore()[source]#

Show the score as a table

Return type:

None

addScoreLine(line, comment='')[source]#

Add a score line verbatim

Parameters:
  • line (str | list[int | float | str]) – the line to add

  • comment – add a comment to the score line, when written

Return type:

None

addEvent(instr, start, dur, args=None, comment='', numdigits=8)[source]#

Add an instrument (“i”) event to the score

Parameters:
  • instr (int | float | str) – the instr number or name, as passed to addInstr

  • start (float) – the start time

  • dur (float) – the duration of the event

  • args (Optional[Sequence[float | str]]) – pargs beginning at p4

  • numdigits – if given, round start and duration to this number of digits

  • comment – if given, the text is attached as a comment to the event line in the score

Return type:

None

strset(s, index)[source]#

Add a strset to this csd

If s has already been passed, the same index is returned

Return type:

int

addTableFromData(data, tabnum=0, start=0.0, filefmt='', sr=0)[source]#

Add a table definition with the data

Parameters:
  • data (Union[Sequence[float], ndarray]) – a sequence of floats to fill the table. The size of the table is determined by the size of the seq.

  • tabnum (int) – 0 to auto-assign an index

  • start – allocation time of the table

  • filefmt – format to use when saving the table as a datafile. If not given, the default is used. Possible values: ‘gen23’, ‘wav’

  • sr (int) – if given and data is a numpy array, it is saved as a soundfile and loaded via gen1

Return type:

int

Returns:

the table number

Note

The data is either included in the table definition (if it is small enough) or saved as an external file. All external files are saved relative to the generated .csd file when writing. Table data is saved as 32 bit floats, so it might loose some precission from the original.

addEmptyTable(size, tabnum=0, sr=0, numchannels=1, time=0.0)[source]#

Add an empty table to this Csd

A table remains valid until the end of the csound process or until the table is explicitely freed (see freeTable())

Parameters:
  • tabnum (int) – use 0 to autoassign an index

  • size (int) – the size of the empty table

  • sr (int) – if given, set the sr of the empty table to the given sr

  • numchannels – the number of channels in the table

  • time – when to do the allocation.

Return type:

int

Returns:

The index of the created table

freeTable(tabnum, time)[source]#

Free a table

Parameters:
  • tabnum (int) – the table number

  • time (float) – when to free it

addSndfile(sndfile, tabnum=0, start=0.0, skiptime=0.0, chan=0, asProjectFile=False)[source]#

Add a table which will load this sndfile

Parameters:
  • sndfile (str) – the output to load

  • tabnum – fix the table number or use 0 to generate a unique table number

  • start – when to load this output (normally this should be left 0)

  • skiptime – begin reading at skiptime seconds into the file.

  • chan – channel number to read. 0 denotes read all channels.

  • asProjectFile – if True, the sndfile is included as a project file and copied to a path relative to the .csd when writing

Return type:

int

Returns:

the table number

destroyTable(tabnum, time)[source]#

Schedule ftable with index source to be destroyed at time time

Parameters:
  • tabnum (int) – the index of the table to be destroyed

  • time (float) – the time to destroy it

Return type:

None

setEndMarker(time)[source]#

Add an end marker to the score

This is needed if, for example, all events are endless events (with dur == -1).

If an end marker has been already set, setting it later will remove the previous endmarker (there can be only one)

Return type:

None

removeEndMarker()[source]#

Remove the end-of-score marker

Return type:

None

setComment(comment)[source]#

Add a comment to the renderer output soundfile

Return type:

None

setOutfileFormat(fmt)[source]#

Sets the format for the output soundfile

If this is not explicitely set it will be induced from the output soundfile set when running the csd

Parameters:

fmt (str) – the format to use (‘wav’, ‘aif’, ‘flac’, etc)

Return type:

None

setSampleEncoding(encoding)[source]#

Set the sample encoding for recording

If not set, csound’s own default for encoding will be used

Parameters:

encoding (str) – one of ‘pcm16’, ‘pcm24’, ‘pcm32’, ‘float32’, ‘float64’

Return type:

None

setCompressionQuality(quality=0.4)[source]#

Set the compression quality

Parameters:

quality – a value between 0 and 1

Return type:

None

setCompressionBitrate(bitrate=128, format='ogg')[source]#

Set the compression quality by defining a bitrate

Parameters:
  • bitrate – the bitrate in kB/s

  • format – the format used (only ‘ogg’ at the moment)

Return type:

None

scoreDuration()[source]#

Returns the duration of this score

If the end marker was set, this will determine the returned duration

Return type:

float

addInstr(instr, body, instrComment='', extranames=None)[source]#

Add an instrument definition to this csd

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

  • body (str) – the body of the instrument (the part between ‘instr’ / ‘endin’)

  • instrComment – if given, it will be added at the end of the ‘instr’ line

  • extranames (list[int | str] | None) – an instr can have multiple names/numbers assigned

Return type:

None

addOpcode(name, outargs, inargs, body)[source]#

Add an opcode to this csd

Parameters:
  • name (str) – the opcode name

  • outargs (str) – the output arguments

  • inargs (str) – the input arguments

  • body (str) – the body of the opcode

Return type:

None

Example

csd.addOpcode("gain", "a", "ak", r'''
  asig, kgain xin
  asig *=kgain
  xout asig
''')
addGlobalCode(code, acceptDuplicates=True)[source]#

Add code to the instr 0

Parameters:
  • code (str) – code to add

  • acceptDuplicates – add copies of the same code even if the same csound code has already been added

Return type:

None

addOptions(*options)[source]#

Adds options to this csd

Options are any command-line options passed to csound itself or which could be used within a <CsOptions> tag. They are not checked for correctness

Return type:

None

dump()[source]#

Returns a string with the .csd

Return type:

str

playTable(tabnum, start, dur=-1, gain=1.0, speed=1.0, chan=1, fade=0.05, skip=0.0)[source]#

Add an event to play the given table

Parameters:
  • tabnum (int) – the table number to play

  • start (float) – schedule time (p2)

  • dur (float) – duration of the event (leave -1 to play until the end)

  • gain – a gain factor applied to the table samples

  • chan

    ??

  • fade – fade time (both fade-in and fade-out

  • skip – time to skip from playback (enables playback to crop a fragment at the beginning)

Return type:

None

Example

>>> csd = Csd()
>>> source = csd.addSndfile("stereo.wav")
>>> csd.playTable(source, source, start=1, fade=0.1, speed=0.5)
>>> csd.write("out.csd")
write(csdfile)[source]#

Write this as a .csd

Any data files added are written to a folder <csdfile>.assets besides the generated .csd file.

Parameters:

csdfile (str) – the path to save to

Return type:

None

Example

>>> from csoundengine.csd import Csd
>>> csd = Csd(...)
>>> csd.write("myscript.csd")

This will generate a myscript.csd file and a folder myscript.assets holding any data file needed. If no data files are used, no .assets folder is created

render(outfile='', verbose=False)[source]#

Render this csd offline

Parameters:
  • outfile – the soundfile to generate, if not given a tempfile is used

  • verbose – output rendering information. If False, stdout and stderr can still be read through the Popen object

Return type:

RenderJob

Returns:

a RenderJob object

run(output, csdfile='', inputdev='', backend='', suppressdisplay=True, nomessages=False, piped=False, extraOptions=None)[source]#

Run this csd.

Parameters:
  • output (str) – the output of the csd. This will be passed as the -o argument to csound. If an empty string or None is given, no sound is produced (adds the ‘–nosound’ flag).

  • inputdev – the input device to use when running in realtime

  • csdfile – if given, the csd file will be saved to this path and run from it. Otherwise a temp file is created and run.

  • backend – the backend to use

  • suppressdisplay – if True, display (table plots, etc.) is supressed

  • nomessages – if True, debugging scheduling information is suppressed

  • piped – if True, stdout and stderr are piped through the Popen object, accessible through .stdout and .stderr streams

  • extraOptions (list[str] | None) – any extra args passed to the csound binary

Return type:

RenderJob

Returns:

a RenderJob holding a subprocess.Popen object

setPfield(p1, pindex, value, start)[source]#

Set the value of a pfield for a scheduled event

Parameters:
  • p1 (int | float | str) – the instr number/name of the event

  • pindex (int) – the index of the pfield, 4=p4, 5=p5, etc

  • value (float) – the new value of the pfield

  • start (float) – when to set the pfield (absolute time)

Return type:

None

automatePfield(p1, pindex, pairs, start)[source]#

Automate the pfield of a scheduled event

Parameters:
  • p1 (int | float | str) – the instr number/name of the event

  • pindex (int) – the index of the pfield

  • pairs (Sequence[float]) – a flat sequence of breakpoints of the form [time0, value0, time1, value1, …]

  • start (float) – absolute time to start the automation

Return type:

None