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
.csdfileinspect the audio environment
query different paths used by csound
etc.
Functions#
|
Return a list of audio backends for the given platform |
Given an extension, return the best sample encoding. |
|
|
Channel type (k, S, a) from value |
|
Convert a bitrate to a compression quality between 0-1, as passed to --vbr-quality |
|
Convert compression quality to bitrate |
|
Returns the command-line option for the given sample encoding. |
|
Returns the command-line options for the given format+encoding |
|
Calls csound with given args in a subprocess, returns a subprocess.Popen object. |
Prints all available backends and their properties as a table |
|
|
Print a list of audio devices for the given backend. |
|
Dump information about audio backends and audio devices for the selected backend |
|
|
|
Read a file saved by ftsave, returns a list of tables |
|
Given the name of the backend, return the AudioBackend structure |
|
Returns a list with the names of the audio backends for a given platform |
|
Returns (indevices, outdevices), where each of these lists is an AudioDevice. |
|
Returns the default audio devices for a given backend |
Get the default active backend for platform |
|
|
Get the default number of channels for a given device |
|
Returns the samplerate reported by the given backend |
|
Get the system samplerate for a given backend |
|
Returns the csound version as tuple (major, minor, patch) |
|
Converts csound code to html with syntax highlighting |
|
Return a list of the opcodes present |
|
|
|
Returns the list of names/instrument numbers in the instrument definition. |
|
Parses the body of an instrument, returns pfields used, output channels, etc. |
|
Is name a pfield? |
|
Joins an orc and a score (both as str), returns a csd as string |
|
Line of the last assignment to a variable |
|
Locate the docstring in this instr code |
|
Given a path, creates the #include directive |
|
Returns input and output midi devices for the given backend |
|
Stretch/Pitchshift a output using csound's mincer opcode (offline) |
|
Returns the power of 2 higher or equal than n |
|
Transform name so that it can be accepted as an instrument name |
|
Given a dict mapping pfield as str to value, return a dict mapping pfield index to value |
|
Parse orchestra code into blocks |
|
Record one instrument for a given duration |
|
Run the given .csd as a csound subprocess |
|
Saves the data to a gen23 table |
|
Save a numpy 2D array as gen23 |
|
Save data in wav format using the mtx extension |
|
Make a SoundFontIndex for the given soundfont |
|
Get the instrument number from a preset |
|
Get instruments for a soundfont |
|
|
|
|
|
Get presets from a soundfont |
|
Select a preset from a soundfont interactively |
|
|
|
Given an include line it splits the include path |
|
|
|
Test the current csound installation for realtime output |
|
Returns the user plugins folder for this platform |
Classes#
|
Special type indicating an unconstrained type. |
|
Holds information about a csound audio backend |
|
An AudioDevice holds information about a an audio device for a given backend |
|
A CsoundProc wraps a running csound subprocess |
|
A MidiDevice holds information about a midi device for a given backend |
|
A ParsedBlock represents a block (an instr, an opcode, etc) in an orchestra |
|
The result of parsing the body of an instrument |
|
Represent an offline render process |
|
Creates an index of presets for a given soundfont |
|
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 audioksmps (
int) – the samples per cycle to usenchnls (
int) – the number of output channelsnchnls_i (
int|None) – if given, the number of input channelsa4 (
float) – the reference frequencyoptions (
list[str] |None) – any number of command-line options passed to csoundnodisplay – 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 usesftgen
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:
The score, a list of ScoreLine
The orchestra
User defined opcodes
Code to evaluate at the instr0 level
Command line options
Samples per cycle
Number of output channels
Number of input channels
Reference frequency
Disable display opcodes
Enable carry in the score
Number of threads used for rendering
Maps assigned table numbers to their metadata
Samplerate
Methods:
copy()Copy this csd
cropScore([start, end])Crop the score at the given boundaries
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
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
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
- 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
- addScoreLine(line, comment='')[source]#
Add a score line verbatim
- Parameters:
line (
str|list[int|float|str]) – the line to addcomment – 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 addInstrstart (
float) – the start timedur (
float) – the duration of the eventargs (
Optional[Sequence[float|str]]) – pargs beginning at p4numdigits – 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
shas 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 indexstart – 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 indexsize (
int) – the size of the empty tablesr (
int) – if given, set the sr of the empty table to the given srnumchannels – 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 numbertime (
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 loadtabnum – 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 destroyedtime (
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
- 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 namebody (
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 nameoutargs (
str) – the output argumentsinargs (
str) – the input argumentsbody (
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 addacceptDuplicates – 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
- 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 playstart (
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.csdfile and a foldermyscript.assetsholding any data file needed. If no data files are used, no.assetsfolder 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:
- 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:
- 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 eventpindex (
int) – the index of the pfield, 4=p4, 5=p5, etcvalue (
float) – the new value of the pfieldstart (
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 eventpindex (
int) – the index of the pfieldpairs (
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