CsoundUnity 4.0.0-alpha.3
Loading...
Searching...
No Matches
Csound.Unity.CsoundUnity Class Reference

Runs Csound inside a scene: compiles a .csd, performs it while the scene plays, and exposes its channels to the rest of the game. More...

Inheritance diagram for Csound.Unity.CsoundUnity:

Public Types

enum  EnvType {
  SFDIR , SSDIR , SADIR , SFOUTYP ,
  INCDIR , OPCODE7DIR , OPCODE7DIR64 , SNAPDIR ,
  CSOUND7RC , CSSTRNGS , CS_LANG , RAWWAVE_PATH ,
  CSNOSTOP , MFDIR , CS_OMIT_LIBS , CS_USER_PLUGINDIR ,
  CS_UDO_DIR
}
 The enum representing the Csound Environment Variables. More...
enum  DiscreteChannelMode { SnapAtEnd , SnapAtMidpoint , SnapAtStart }
 Controls how discrete channels (button, checkbox, combobox) are handled during MorphToPreset. More...
enum  DiscreteBlendMode { Ignore , NearestCorner }
 Controls how discrete channels (button, checkbox, combobox) are handled during BlendPresets. More...

Public Member Functions

CsoundArrayChannelStatus InitializeArrayChannel (string name, CsoundArrayChannelType type, params int[] sizes)
 Create an i[], k[], S[] or a[] channel, or verify an existing channel's exact type and shape. Initialization may allocate and briefly suspend Unity audio processing; call during setup, never from an audio callback. Existing channels are not resized.
CsoundArrayChannelStatus GetArrayChannelInfo (string name, int[] sizes, out CsoundArrayChannelInfo info)
 Read array metadata and axis sizes without creating a channel or allocating a buffer.
CsoundArrayChannelStatus GetArrayChannel (string name, MYFLT[] destination, out int length)
 Copy a numeric array into a reusable flat buffer; unused trailing entries are unchanged.
CsoundArrayChannelStatus GetArrayChannel (string name, MYFLT[] destination, int[] sizes, out CsoundArrayChannelInfo info)
 Copy numeric data and its axis sizes under one channel lock, including when producers resize.
CsoundArrayChannelStatus SetArrayChannel (string name, MYFLT[] source)
 Replace all numeric elements of the channel's current shape; source length must match exactly.
CsoundArrayChannelStatus GetAudioArrayChannel (string name, MYFLT[] destination, out int length)
 Copy an audio array into a reusable flat buffer; unused trailing entries are unchanged.
CsoundArrayChannelStatus GetAudioArrayChannel (string name, MYFLT[] destination, int[] sizes, out CsoundArrayChannelInfo info)
 Copy audio blocks and their axis sizes under one channel lock, including when producers resize.
CsoundArrayChannelStatus SetAudioArrayChannel (string name, MYFLT[] source)
 Replace all audio samples of the channel's current shape; source length must match exactly.
CsoundArrayChannelStatus GetStringArrayChannel (string name, string[] destination, out int length)
 Read a complete string array into a reusable container. Changed strings allocate; unchanged values retain their references. Runs outside audio callbacks and does not create a channel.
CsoundArrayChannelStatus GetStringArrayChannel (string name, string[] destination, int[] sizes, out CsoundArrayChannelInfo info)
 Read UTF-8 string values and their matching shape atomically; decode outside the native spin lock.
CsoundArrayChannelStatus SetStringArrayChannel (string name, string[] source)
 Replace all S[] elements from UTF-8 text without resizing the channel. Null elements become empty strings; embedded null characters are rejected. Native buffers may grow. Not audio-thread safe.
AudioRouteResult AddAudioInputRoute (CsoundUnity source, string sourceChannelName, int destSpinChannel=0, float level=1f, bool forceConnection=false)
 Adds a new audio input route to this instance at runtime.
void RemoveAudioInputRoute (int index)
 Removes the audio input route at index in audioInputRoutes.
void RemoveAudioInputRoute (CsoundUnity source)
 Removes all audio input routes whose source is source .
void RemoveAudioInputRoute (CsoundUnity source, string sourceChannelName, int destSpinChannel)
 Removes the specific audio input route that matches all three key fields.
void RemoveAllAudioInputRoutes ()
 Removes all audio input routes from this instance.
bool WouldCreateCircle (CsoundUnity newSource)
 Returns true if routing audio from newSource into this instance would create a circular dependency in the audio graph.
void SetChannel (string channel, MYFLT val)
 Sets a Csound channel. Used in connection with a chnget opcode in your Csound instrument.
void SetChannel (CsoundChannelController channelController)
 Sets a Csound channel. Useful for setting presets at runtime. Used in connection with a chnget opcode in your Csound instrument.
void SetChannels (List< CsoundChannelController > channelControllers, bool excludeButtons=true)
 Sets a list of Csound channels.
void SetStringChannel (string channel, string val)
 Sets a string channel in Csound. Used in connection with a chnget opcode in your Csound instrument.
MYFLT GetChannel (string channel)
 Gets a Csound channel. Used in connection with a chnset opcode in your Csound instrument, or set with SetChannel.
void GetChannel (string channel, Action< MYFLT > callback)
 Reads a Csound control channel and delivers the result via callback . On non-WebGL platforms the callback is invoked synchronously before this method returns. On WebGL the read is dispatched to the AudioWorklet thread; the callback fires on the main thread once the value is available (typically within the same or the next frame).
CsoundChannelController GetChannelController (string channel)
 Returns the serialized CsoundChannelController for the named channel, as parsed from the CSD file by ParseCsdFile.
string GetStringChannel (string name)
 Get a Csound string channel. Used in connection with a chnset opcode in your Csound instrument, or set with SetStringChannel.
IDictionary< string, CsoundUnityBridge.ChannelInfo > GetChannelList ()
 Blocking method to get a list of the channels from Csound, not from the serialized list of this instance. Provides a dictionary of all currently defined channels resulting from compilation of an orchestra containing channel definitions. Entries, keyed by name, are polymorphically assigned to their correct data type: control, audio, string, pvc.
MYFLT[] GetAudioChannel (string channel)
 Gets a Csound Audio channel. Used in connection with a chnset opcode in your Csound instrument.
void GetAudioChannel (string channel, MYFLT[] dest)
 Zero-allocation overload: reads the named audio channel directly into dest without any managed or native heap allocation. Prefer this on hot audio-thread paths (e.g. inside OnAudioFilterRead or a ksmps callback) to avoid GC pressure and the periodic audio dropouts it causes.
void AddAudioChannel (string channel)
 Add an audio channel to the list that can be used in CsoundUnityChild.
void RemoveAudioChannel (string channel)
 Removes an audio channel from the list that can be used in CsoundUnityChild.
double GetAudioChannelSample (string channel, int sample)
 Returns a sample from a CsoundUnity audio channel This is useful if you want to update an AudioSource using the OnAudioFilterRead callback Internally it uses the namedAudioChannelDataDict buffer, that is usually used to update CsoundUnityChild scripts Using this together with AddAudioChannel(string) and RemoveAudioChannel(string) allows you to create new audio channels at runtime.
void ResetDspLoadStatistics ()
 Requests a statistics reset at the next measured DSP block. Call from the main thread. Measurement must be enabled for the reset to take effect.
delegate void CsoundInitialized ()
 The delegate of the event OnCsoundInitialized.
delegate void ChannelsUpdated ()
 The delegate of the event OnChannelsUpdated.
void NotifyChannelsUpdated ()
 Raises OnChannelsUpdated. Call it after writing several channels yourself with SetChannel(string, MYFLT), so the UI components re-read them.
delegate void CsoundStopped ()
 The delegate of the event OnCsoundStopped.
delegate void CsoundPerformKsmps ()
 The delegate of the event OnCsoundPerformKsmps.
delegate void CsoundPerformanceFinishedDelegate ()
 The delegate of the event OnCsoundPerformanceFinished.
void Initialize ()
 Initializes CsoundUnity manually. Only works if initializeOnAwake is false, or after a Stop. Silently returns if already initialized or initializing.
void Stop ()
 Stops and disposes the current Csound instance. After this, Initialize or Restart can be called to start again.
void Restart ()
 Stops the current Csound instance and reinitializes it from scratch.
int GetVersion ()
 Returns the Csound version number times 1000 (5.00.0 = 5000).
int LoadPlugins (string dir)
 Loads all plugins from a given directory.
bool CompiledWithoutError ()
 Returns true if the csd file was compiled without errors.
void SetInputSample (int frame, int channel, MYFLT sample)
 Set a sample in Csound's input buffer, overwriting any existing value.
void AddInputSample (int frame, int channel, MYFLT sample)
 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 nchnls. NB: the spin buffer needs to be cleared at every k-cycle by calling ClearSpin().
void ClearSpin ()
 Clears the input buffer (spin).
MYFLT GetOutputSample (int frame, int channel)
 Get a sample from Csound's audio output buffer.
MYFLT[] GetSpin ()
 Get Csound's audio input buffer.
MYFLT[] GetSpout ()
 Get Csound's audio output buffer.
string GetEnv (EnvType envType)
 Get Environment path.
int SetGlobalEnv (string name, string value)
 Set the global value of environment variable 'name' to 'value', or delete variable if 'value' is NULL. It is not safe to call this function while any Csound instances are active. See https://csound.com/docs/manual/CommandEnvironment.html for a list of the variables that can be used.
uint GetNchnlsInputs ()
 Get the number of input channels.
uint GetNchnls ()
 Get the number of output channels.
MYFLT Get0dbfs ()
 Get the 0 dBFS amplitude reference value as set by the 0dbfs statement in the orchestra.
long GetCurrentTimeSamples ()
 Returns the current performance time in samples.
bool CsoundReset ()
 Returns the Csound instance to its pre-compilation state, keeping it alive and reusable: the orchestra and the control channels are gone afterwards. Compile again before performing, and set the channel values again. The engine settings are re-armed here, so the instance keeps the host sample rate, ksmps and audio IO it was created with.
AudioChannelReader GetAudioChannelReader (string channelName)
 Returns a reader for the audio this instance publishes on a named audio channel: one finished block at a time, readable from any thread.
GeneratorInstance CreateInstance (ControlContext context, AudioFormat? nestedFormat=null, ProcessorInstance.CreationParameters creationParameters=default)
 Called by Unity when AudioSource.generator = this is set (or when a scene with a serialized generator reference is loaded). Creates the unmanaged CsoundRealtime and CsoundControl structs and hands them to Unity via context.AllocateGenerator.
void SetCsd (string guid)
 Sets the CSD from a project asset, identified by its AssetDatabase GUID.
bool LoadCsdFromString (string csdContent, bool startNow=true)
 Loads a CSD from a raw string at runtime, without requiring a .csd asset.
bool LoadCsdFromPath (string path, bool startNow=true)
 Reads a CSD from a file and loads it, the runtime counterpart of assigning a csd asset. Equivalent to reading the file yourself and calling LoadCsdFromString.
void LoadCsdFromPath (string path, Action< bool > onLoaded, bool startNow=true)
 Reads a CSD with UnityWebRequest and loads it, then reports the outcome to onLoaded . Works for the cases the synchronous overload refuses: StreamingAssets on any platform, and http/https URLs.
int CompileOrc (string orcStr)
 Parse, and compile the given orchestra from an ASCII string, also evaluating any global space code (i-time only) this can be called during performance to compile a new orchestra. This sample shows how to use CompileOrc.
int CsoundStart ()
 Starts the compiled orchestra after CsoundReset and enables performance. Call CompileOrc first. Starting an already running instance is a no-op.
void SendScoreEvent (string scoreEvent)
 Send a score event to Csound in the form of "i1 0 10 ....
void RewindScore ()
 Rewinds a compiled Csound score to the time specified with SetScoreOffsetSeconds().
void SetScoreOffsetSeconds (MYFLT value)
 Csound score events prior to the specified time are not performed, and 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.
MYFLT GetSr ()
 Get the current sample rate.
MYFLT GetKr ()
 Get the current control rate.
int PerformKsmps ()
 Process a ksmps-sized block of samples.
uint GetKsmps ()
 Get the number of audio sample frames per control sample.
void SavePresetAsScriptableObject (string presetName, string path=null)
 Save a CsoundUnityPreset of this CsoundUnity instance at the specified path, using the specified presetName. The current csoundFileName and list of CsoundChannelControllers will be saved in the preset. If no presetName is given, a default one will be used.
void SavePresetAsJSON (string presetName, string path=null, bool overwriteIfExisting=false)
 Save a preset as JSON using CsoundChannelControllers and CsoundFileName from this CsoundUnity instance. See SavePresetAsJSON(CsoundUnityPreset, string, bool).
void SaveGlobalPreset (string presetName, string path=null, bool overwriteIfExisting=false)
 Save a serialized copy of this CsoundUnity instance. Similar behaviour as saving a Unity Preset from the inspector of the CsoundUnity component, but this can be used at runtime.
void ConvertPresetToScriptableObject (string path, string destination)
 Convert a JSON preset into a Scriptable Object preset to be written at the specified path. If path is empty the converted preset will be saved inside the Assets folder.
CsoundUnityPreset SetPreset (string presetName, string presetData)
 Set a CsoundUnityPreset to this CsoundUnity instance using a presetName and presetData. The set preset will be returned.
CsoundUnityPreset SetPreset (string presetData)
 Set a CsoundUnityPreset to this CsoundUnity instance using presetData.
void SetPreset (CsoundUnityPreset preset)
 Set a CsoundUnityPreset to this CsoundUnity instance.
CsoundUnity SetGlobalPreset (string presetName, string presetData)
 Set a global preset to this CsoundUnity instance using a presetName and presetData.
void LoadPreset (string path, Action< CsoundUnityPreset > onPresetLoaded=null)
 Loads a preset from a JSON file. The JSON file should represent a CsoundUnityPreset.
void LoadGlobalPreset (string path)
 Load a global preset on this CsoundUnity instance from a JSON file found at path. The JSON file should represent a Global Preset, ie a complete CsoundUnity instance.
Coroutine MorphToPreset (CsoundUnityPreset preset, float duration, AnimationCurve curve=null, Action onComplete=null, DiscreteChannelMode discreteMode=DiscreteChannelMode.SnapAtEnd)
 Smoothly interpolates all continuous channels — the sliders, plus both axes of an xypad, hrange or vrange — from their current values to the target preset's values over the given duration. An optional AnimationCurve controls easing; pass null for linear interpolation. The returned Coroutine can be passed to StopMorph to cancel mid-way. If duration is zero or negative, the preset is applied immediately.
void StopMorph ()
 Stops an in-progress morph started by MorphToPreset. Channel values remain at whatever point the morph reached when stopped.
void BlendPresets (CsoundUnityPreset a, CsoundUnityPreset b, CsoundUnityPreset c, CsoundUnityPreset d, Vector2 position, DiscreteBlendMode discreteMode=DiscreteBlendMode.Ignore)
 Bilinear blend of four presets placed at the corners of a unit square.
bool CopyChannelsToClipboard ()
 Puts this instance's control channels on the system clipboard, as the same JSON a CsoundUnityPreset is saved in — so a clipboard snapshot and a saved .json preset are interchangeable, and channels can be pasted into a chat window as readily as back into an inspector.
bool PasteChannelsFromClipboard ()
 Applies channels held on the clipboard in the CsoundUnityPreset JSON format.
CsoundPvsChannelStatus InitializePvsChannel (string name, int fftSize, int overlap, int windowSize, int windowType=1, CsoundPvsFormat format=CsoundPvsFormat.AmplitudeFrequency)
 Create or verify a fixed-layout PVS channel during setup. May allocate and briefly suspend Unity audio.
CsoundPvsChannelStatus GetPvsChannelInfo (string name, out CsoundPvsChannelInfo info)
 Read PVS layout and frame counter without creating a channel.
CsoundPvsChannelStatus GetPvsChannel (string name, float[] destination, out CsoundPvsChannelInfo info)
 Read a complete N+2 float frame and matching metadata; neither partial copies nor channel creation occur.
CsoundPvsChannelStatus SetPvsChannel (string name, float[] source)
 Write exactly N+2 floats and increment the frame counter on success. Use once per new spectral frame.
CsoundPvsChannelStatus SetPvsChannel (string name, float[] source, CsoundPvsChannelInfo frame)
 Write a snapshot with matching FFT/hop/window/format, preserving its frame counter.
int CreateFloatTable (int tableNumber, float[] samples)
 Creates a table with the supplied float samples. Can be called during performance.
int CreateTable (int tableNumber, MYFLT[] samples)
 Creates a table with the supplied samples. Can be called during performance.
int CreateTableInstrument (int tableNumber, int tableLength)
 Creates an empty table, to be filled with samples later. Please note that trying to read the samples from an empty folder will produce a crash. Can be called during performance.
int GetTableLength (int table)
 Returns the length of a function table (not including the guard point), or -1 if the table does not exist.
MYFLT GetTableSample (int tableNumber, int index)
 Retrieves a single sample from a Csound function table.
int GetTable (out MYFLT[] tableValues, int numTable)
 Stores values to function table 'numTable' in tableValues, and returns the table length (not including the guard point). If the table does not exist, tableValues is set to NULL and -1 is returned.
int GetTableArgs (out MYFLT[] args, int index)
 Stores the arguments used to generate function table 'tableNum' in args, and returns the number of arguments used. If the table does not exist, args is set to NULL and -1 is returned. NB: 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}.
void SetTable (int table, int index, MYFLT value)
 Sets the value of a slot in a function table. The table number and index are assumed to be valid.
void CopyTableOut (int table, out MYFLT[] dest)
 Copy the contents of a function table into a supplied array dest The table number is assumed to be valid, and the destination needs to have sufficient space to receive all the function table contents.
void CopyTableOutAsync (int table, out MYFLT[] dest)
 Queues a read into an array filled during a later performance cycle.
CsoundTableCopySubmission CopyTableOutAsync (int table, out MYFLT[] dest, out CsoundTableCopyRequest request)
 Queues a table read and returns the destination and a request to poll on the calling thread.
void CopyFloatTableIn (int table, float[] source)
 Same as CopyTableIn but passing a float array.
void CopyTableIn (int table, MYFLT[] source)
 Copy the contents of a supplied array into a function table The table number is assumed to be valid, and the destination needs to have sufficient space to receive all the function table contents.
void CopyTableInAsync (int table, MYFLT[] source)
 Queues a snapshot of the source for a later performance cycle.
CsoundTableCopySubmission CopyTableInAsync (int table, MYFLT[] source, out CsoundTableCopyRequest request)
 Queues a table write and returns a request to poll on the calling thread.
void SendMidiNoteOn (int channel, int note, int velocity)
 Sends a MIDI Note On message to Csound. The CSD must have a MIDI device option (e.g. <CsOptions> -M0 </CsOptions>) for Csound to process MIDI events.
void SendMidiNoteOff (int channel, int note, int velocity=0)
 Sends a MIDI Note Off message to Csound.
void SendMidiControlChange (int channel, int controller, int value)
 Sends a MIDI Control Change message to Csound.
void SendMidiProgramChange (int channel, int program)
 Sends a MIDI Program Change message to Csound.
void SendMidiMessage (byte[] data)
 Sends a raw MIDI message (1–3 bytes) directly to Csound. Use this for any MIDI message type not covered by the helper methods above.

Static Public Member Functions

static int ParseCsdFileForNchnls (string filename)
 Reads the CSD file and returns the value of nchnls (output channels) declared in the orchestra header. Correctly ignores nchnls_i (input channels). Returns 0 when the directive is absent — in that case Csound defaults to 1, but callers should treat 0 as "unknown / not specified".
static int ParseCsdStringForNchnls (string csdContent)
 String equivalent of ParseCsdFileForNchnls, used when only the CSD content is available (no file path), e.g. from LoadCsdFromString.
static int ParseCsdFileForKsmps (string filename)
 Parses ksmps from the global header of the CSD's <CsInstruments> section. Returns the explicit ksmps value if declared; otherwise computes round(sr / kr) if both are present; otherwise returns 0 (not specified). Only scans lines before the first instr declaration.
static int ParseCsdStringForKsmps (string csdContent)
 String equivalent of ParseCsdFileForKsmps, used when only the CSD content is available (no file path), e.g. from LoadCsdFromString.
static List< string > ParseCsdFileForAudioChannels (string filename)
 Parses the CSD file and returns the names of all audio-rate channels declared via chnset avar, "channel name" (channels driven by a- or ga-rate variables with literal string names).
static List< string > ParseCsdStringForUnsupportedWidgets (string csdContent)
 Cabbage widget names that appear in a csd but that the parser does not build a channel for, so the inspector and the UI generator can say so instead of silently showing less than the csd declares.
static List< string > ParseCsdStringForAudioChannels (string csdContent)
 Parses a CSD string (already in memory) for named audio channels written with chnset. Runtime equivalent of ParseCsdFileForAudioChannels used when only the CSD content is available (no file path), e.g. during Init on first play after a fresh package import where the inspector was never opened to trigger SetCsd.
static List< CsoundChannelController > ParseCsdFile (string filename)
 Parses the CSD file's Cabbage widget section and returns a list of CsoundChannelController objects describing every slider, button, checkbox, combobox, xypad, and similar widget found.
static List< CsoundChannelController > ParseCsdString (string csdContent)
 String equivalent of ParseCsdFile — parses the Cabbage widget section from CSD text already in memory (no file path), e.g. from LoadCsdFromString.
static CsoundUnityPreset CreatePreset (string presetName, string csoundFileName, List< CsoundChannelController > channels)
 Create a CsoundUnityPreset from a presetName, csoundFileName and a list of CsoundChannelControllers.
static CsoundUnityPreset CreatePreset (string presetName, string presetData)
 Create a CsoundUnityPreset from a presetName and presetData.
static void WritePreset (CsoundUnityPreset preset, string path)
 Write a CsoundUnityPreset at the specified path inside the Assets folder. You can pass a full path, the Assets folder path will be extracted. Subfolders in the preset name are created as needed; the stored name is the file's leaf name. Overwriting an existing asset preserves its GUID and references.
static void SavePresetAsJSON (CsoundUnityPreset preset, string path=null, bool overwriteIfExisting=false)
 Save the specified CsoundUnityPreset as JSON, at the specified path. If a file exists at the specified path, it will be overwritten if overwriteIfExisting is true.
static void SavePresetAsJSON (List< CsoundChannelController > channels, string csoundFileName, string presetName, string path=null, bool overwriteIfExisting=false)
 Save a preset as JSON from a list of CsoundChannelController, specifying the related CsoundFileName and the presetName. See SavePresetAsJSON(CsoundUnityPreset, string, bool).
static List< CsoundUnityPreset > ParseSnap (string csdPath, string snapPath)
 Parses a Cabbage .snaps file and returns a list of CsoundUnityPreset objects, one per snapshot entry, with channel metadata filled in from the companion CSD.

Public Attributes

bool logCsoundOutput = false
 If true, all Csound output messages will be sent to the Unity output console. Note that this can slow down performance if there is a lot of information being printed.
bool initializeOnAwake = true
 If true CsoundUnity will initialize automatically in Awake. Set to false to initialize manually by calling Initialize.
bool mute = false
 Silences this instance's audio output. Csound keeps performing: the score advances, so unmuting drops back in on the beat rather than resuming where it left off, and input (audio input routes, native audio input, clip audio) keeps flowing in.
bool pauseProcessing = false
 Suspends this instance: the output is silenced and Csound stops performing, so no DSP work is done at all. The score is frozen, so clearing the flag resumes from exactly where it stopped.
bool processClipAudio
 If true Csound uses as an input the AudioClip attached to this AudioSource. If false, no processing occurs on the attached AudioClip.
bool loudVolumeWarning = true
 If true it will print warnings in the console when the output volume is too high, and clamp every sample louder than loudWarningThreshold to it.
float loudWarningThreshold = 10f
 The ceiling: a sample louder than this is clamped to it, and the console names the level it reached. 1 is full scale, so the default of 10 only catches real runaways.
bool overrideSamplingRate = false
 If true you can override the default Csound control rate with a custom value. The default value is AudioSettings.outputSampleRate. Ksmps will be calculated by Csound so there's no need to set it in your csd.
int audioRate = 44100
 The audio sample rate (sr) passed to Csound on initialization. Defaults to AudioSettings.outputSampleRate unless overrideSamplingRate is true.
int controlRate = 44100
 The Csound control rate (kr) computed as audioRate / ksmps. Updated automatically whenever audioRate or ksmps changes.
int ksmps = 32
 Intended ksmps value. Stored so that when the audio device changes (sr changes) the control rate is recomputed as kr = sr / ksmps rather than being rounded from the old kr, which would yield a different ksmps.
bool updateOutputBuffer = false
 When true, the full Csound output buffer (all nchnls channels) is copied into OutputBuffer each DSP block, making it available to visualisers and external audio routing. Off by default to avoid the per-block copy overhead.
float fadeInSeconds = 0f
 Ramps the output up from silence over this many seconds when Csound starts, masking the transient of chained sources that have not filled their buffers yet. 0 disables it, which is the default: playback starts at full level.
List< AudioInputRoute > audioInputRoutes = new List<AudioInputRoute>()
 Audio-rate input routes: each entry reads a named audio channel from another CsoundUnity instance and injects it into this instance's spin buffer before every PerformKsmps call.
volatile INativeAudioInputProvider nativeAudioInputProvider
 Optional native audio input provider (e.g. CsoundUnityNativeAudioInput). When set, INativeAudioInputProvider.FillSpinBuffer is called once per ksmps boundary on the audio thread, before PerformKsmps. Assign on the main thread; reads on the audio thread are safe due to the volatile qualifier.
bool muteAudioInputRoutes = false
 When true, all Audio Input Routes are silenced without removing them.
readonly Dictionary< string, MYFLT[]> namedAudioChannelDataDict = new Dictionary<string, MYFLT[]>()
 Named audio channels produced by this instance, shown in the CsoundUnityChild inspector.
string csoundScore
 the score to send via editor
List< EnvironmentSettings > environmentSettings = new List<EnvironmentSettings>()
 The list of the Environment Settings that will be set on start, using csoundSetGlobalEnv. Each setting can be used to specify the path of an environment variable. These settings will be applied to this CsoundUnity instance when the CsoundUnityBridge is created.
List< string > webGLAssetsList
 List of asset paths that will be loaded asynchronously by the WebGL Csound bridge before performance begins (e.g. sample files that must be available in the virtual file system).

Static Public Attributes

const string packageName = "com.csound.csoundunity"
 The name of this package.
const string packageVersion = "4.0.0-alpha.3"
 The version of this package.

Package Functions

CsoundSharedBuffer GetPublishedAudioChannel (string channelName)
 Returns the published snapshot buffer for channelName , or null if this instance has never published that channel.
bool TryApplyPreset (CsoundUnityPreset preset)

Static Package Functions

static bool IsButtonChannel (CsoundChannelController ch)
 A button channel carries an impulse, not a state: the csd zeroes it with its own chnset, which the serialised copy never sees, so a click leaves 1 in the list for good. Everything that pours serialised values back into Csound skips these. A checkbox is excluded: that one does hold a state worth restoring.
static bool IsRestorable (CsoundChannelController ch)
 Whether the clipboard can carry and restore this channel. It needs a name — the csd's form, and any widget without one, is in the list but is not a channel — and a button is excluded because a momentary trigger has no value worth putting back.
static bool CsdRequestsMidi (string csd)
 Whether a csd asks Csound for a MIDI device. Comments are stripped before looking: a line that merely mentions -M, as a comment explaining it does, is not an option.

Static Package Attributes

const string GLOBAL_TAG = "(GLOBAL)"

Properties

string csoundFileGUID [get]
 the unique guid of the csd file
string csoundFileName [get]
 The file CsoundUnity will try to load. You can only load one file with each instance of CsoundUnity, but you can use as many instruments within that file as you wish.You may also create as many of CsoundUnity objects as you wish.
string csoundString [get]
 a string to hold all the csoundFile content
float LoudLimit [get]
 The sample value the audio paths silence a sample at. PositiveInfinity when the check is off, so a sample that is not a number is caught either way: on RootOutput one of those does not stay inside this instance, it goes into Unity's main output.
string samplingRateSettingsInfo [get]
 Returns a human-readable summary of the current sampling-rate settings in the form "sr: X, kr: Y, ksmps: Z". Used by the inspector.
List< CsoundChannelController > channels [get]
 list to hold channel data
List< string > availableAudioChannels [get]
 list to hold available audioChannels names
List< string > unsupportedWidgets [get]
 Cabbage widgets present in the current csd that the parser does not build a channel for. Empty when everything in the csd is supported.
bool IsInitialized [get]
 Is Csound initialized?
bool IsWaitingForUserGesture [get]
 True while a browser is withholding audio until the page gets a real click, tap or key press. Always false off WebGL, so a scene can read it without a platform check.
bool MeasureDspLoad [get, set]
 Turns the DSP load measurement on and off. It costs a little time on the audio thread, so it is off unless something is reading it.
float DspLoad = 0f [get]
 Exponentially smoothed DSP load: fraction of the DSP time budget used by this instance. 0 = idle, 1 = full budget consumed, >1 = overload. Only meaningful when MeasureDspLoad is true.
double DspPeakBlockMilliseconds [get]
 Highest measured DSP block duration in milliseconds since the last reset. Covers the same Csound work as DspLoad; excludes other Unity audio sources. Stays zero until measurement is enabled with MeasureDspLoad; retains its value while measurement is off.
long DspMeasuredBlocks [get]
 Number of DSP blocks measured since the last reset. Stays zero until measurement is enabled with MeasureDspLoad; retains its value while measurement is off.
long DspOverBudgetBlocks [get]
 Measured blocks whose Csound work exceeded the block's audio time budget. This is a timing counter, not a count reported by the audio device. Stays zero until measurement is enabled with MeasureDspLoad; retains its value while measurement is off.
bool PerformanceFinished [get]
 True when Csound's score has ended naturally (all score events have been performed). This is set on the audio thread; for main-thread notification subscribe to OnCsoundPerformanceFinished.
CsoundUnityPreset CurrentPreset [get]
 The preset currently applied to this instance, or null if none is.
string CurrentPresetName [get]
 The name of the current preset, or empty if none is set.
float[] OutputBuffer [get]
 The most recently completed DSP output buffer. Contains interleaved samples for all Csound output channels when updateOutputBuffer is true; otherwise the array holds the single-channel Unity output.
int OutputChannels [get]
 Number of audio channels interleaved in OutputBuffer (equals Csound's nchnls when updateOutputBuffer is true), or 1 before the first block has been published.
int StartupFadeFrames [get]
 Length of the startup fade in output frames, or 0 when fadeInSeconds leaves it off. Plain arithmetic over a sample rate cached on the main thread, so the audio paths can ask for it without calling into Unity.
float LastLoudPeak [get]
 The last peak an audio path had to clamp, and when it happened. The inspector shows them while it is going on: the console can be cleared, filtered, or simply not watched, and the clamp itself sounds like a loud mix rather than like a fault.
float LastLoudTime = float.NegativeInfinity [get]
bool HasCompiled [get]
 true when a CSD was assigned and compiled successfully.
static bool ApplicationIsQuitting [get]
 The static half of IsShuttingDown, for the other components in the package: they make the same main-thread AudioSource calls and need them kept away from FMOD teardown, and this is the part that holds whether or not OnApplicationQuit reached them.
bool isFinite [get]
 Csound runs indefinitely — not finite.
bool isRealtime [get]
 Csound must run at the system audio rate.
DiscreteTime? length [get]
 Infinite generator — length is unknown.
bool WebGLSpatialization [get, set]
 Whether the position is sent to the csd on WebGL.

Events

CsoundInitialized OnCsoundInitialized
 An event that will be executed when Csound is initialized.
ChannelsUpdated OnChannelsUpdated
 Raised after a batch of channels has been written from outside the UI — applying a preset, most of the time.
CsoundStopped OnCsoundStopped
 An event that will be executed when Csound is stopped via Stop.
CsoundPerformKsmps OnCsoundPerformKsmps
 An event fired on the audio thread after every PerformKsmps call. Keep the handler extremely lightweight to avoid audio dropouts.
CsoundPerformanceFinishedDelegate OnCsoundPerformanceFinished
 An event fired on the main thread when Csound performance ends naturally (score complete). CsoundUnity will call Stop immediately after firing this event.

Detailed Description

Runs Csound inside a scene: compiles a .csd, performs it while the scene plays, and exposes its channels to the rest of the game.

Sending MIDI to Csound from C#. The receiving side of the same subsystem is in this folder too: CsoundUnityMidiInput and the per-platform receivers beside it.

IAudioGenerator and RootOutput implementations for CsoundUnity (Unity 6+).

Add it to a GameObject and assign a CSD. An AudioSource is required and added automatically: the audio Csound produces is handed to it, so the mixer, effects and 3D positioning apply as they would to a clip.

Compilation is asynchronous. Check IsInitialized, or subscribe to OnCsoundInitialized, before reading or writing channels.

Several instances can coexist in one scene, each compiling its own CSD, and the named audio channels of one can be routed into the input of another.

This file is a partial extension of CsoundUnity. Depending on CsoundUnity._audioPath:

In both cases the same CsoundUnityBridge is reused, so all existing CsoundUnity API calls continue to work unchanged.

Member Enumeration Documentation

◆ DiscreteBlendMode

Controls how discrete channels (button, checkbox, combobox) are handled during BlendPresets.

Enumerator
Ignore 

Discrete channels are not modified during the blend. Default.

NearestCorner 

Discrete channels take the value from whichever corner currently has the highest weight.

◆ DiscreteChannelMode

Controls how discrete channels (button, checkbox, combobox) are handled during MorphToPreset.

Enumerator
SnapAtEnd 

Discrete channels are applied only at the very end, together with SetPreset. Default.

SnapAtMidpoint 

Discrete channels snap to the target value when the interpolation parameter crosses 0.5.

SnapAtStart 

Discrete channels are set to the target value immediately when the morph begins.

◆ EnvType

The enum representing the Csound Environment Variables.

Enumerator
SFDIR 

Default directory for sound files. Used if no full path is given for sound files.

SSDIR 

Default directory for input (source) audio and MIDI files. Used if no full path is given for sound files. May be used in conjunction with SFDIR to set separate input and output directories. Please note that MIDI files as well as audio files are also sought inside SSDIR.

SADIR 

Default directory for analysis files. Used if no full path is given for analysis files.

SFOUTYP 

Sets the default output file type. Currently only 'WAV', 'AIFF' and 'IRCAM' are valid. This flag is checked by the csound executable and the utilities and is used if no file output type is specified.

INCDIR 

Include directory. Specifies the location of files used by #include statements.

OPCODE7DIR 

Defines the location of csound opcode plugins for the single precision float (32-bit) version.

OPCODE7DIR64 

Defines the location of csound opcode plugins for the double precision float (64-bit) version.

SNAPDIR 

Is used by the FLTK widget opcodes when loading and saving snapshots.

CSOUND7RC 

Points at a Csound configuration file holding command line flags. Only the csound executable reads it, so a host that embeds the library, as CsoundUnity does, is not affected by this setting.

CSSTRNGS 

In Csound 5.00 and later versions, the localisation of messages is controlled by two environment variables CSSTRNGS and CS_LANG, both of which are optional. CSSTRNGS points to a directory containing .xmg files.

CS_LANG 

Selects a language for csound messages.

RAWWAVE_PATH 

Is used by the STK opcodes to find the raw wave files. Only relevant if you are using STK wrapper opcodes like STKBowed or STKBrass.

CSNOSTOP 

If this environment variable is set to "yes", then any graph displays are closed automatically at the end of performance (meaning that you possibly will not see much of them in the case of a short non-realtime render). Otherwise, you need to click "Quit" in the FLTK display window to exit, allowing for viewing the graphs even after the end of score is reached.

MFDIR 

Default directory for MIDI files. Used if no full path is given for MIDI files. Please note that MIDI files are sought in SSDIR and SFDIR as well.

CS_OMIT_LIBS 

Allows defining a list of plugin libraries that should be skipped. Libraries can be separated with commas, and don't require the "lib" prefix. Csound reads this one straight from the process environment, which this setting does not write to.

CS_USER_PLUGINDIR 

Where Csound looks for the user's own plugin opcodes, separately from the opcode directory the package sets for itself. This is the place to put your own opcodes without touching what CsoundUnity ships.

CS_UDO_DIR 

Where Csound looks for User Defined Opcodes (.udo files), so an orchestra can include them by name instead of by path.

Member Function Documentation

◆ AddAudioChannel()

void Csound.Unity.CsoundUnity.AddAudioChannel ( string channel)
inline

Add an audio channel to the list that can be used in CsoundUnityChild.

Parameters
channelThe channel to be added

◆ AddAudioInputRoute()

AudioRouteResult Csound.Unity.CsoundUnity.AddAudioInputRoute ( CsoundUnity source,
string sourceChannelName,
int destSpinChannel = 0,
float level = 1f,
bool forceConnection = false )
inline

Adds a new audio input route to this instance at runtime.

The route injects audio from source 's named channel sourceChannelName into Csound's spin buffer at destSpinChannel before every PerformKsmps.

If adding the route would create a circular dependency (e.g. A→B→A), the method logs a warning and returns false without modifying the list.

Parameters
sourceThe CsoundUnity instance to read audio from.
sourceChannelNameNamed audio channel on the source (e.g. "audioL" or "main_out_0").
destSpinChannelSpin buffer channel index on this instance (default 0).
levelVolume multiplier applied to the source signal (0–2, default 1).
forceConnectionWhen true the route is added even if the source is not initialised yet.
Returns
An AudioRouteResult describing the outcome:

◆ AddInputSample()

void Csound.Unity.CsoundUnity.AddInputSample ( int frame,
int channel,
MYFLT sample )
inline

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 nchnls. NB: the spin buffer needs to be cleared at every k-cycle by calling ClearSpin().

Parameters
frameFrame index within the current ksmps block (0-based).
channelInput channel index (0-based).
sampleThe sample value to add.

◆ BlendPresets()

void Csound.Unity.CsoundUnity.BlendPresets ( CsoundUnityPreset a,
CsoundUnityPreset b,
CsoundUnityPreset c,
CsoundUnityPreset d,
Vector2 position,
DiscreteBlendMode discreteMode = DiscreteBlendMode::Ignore )
inline

Bilinear blend of four presets placed at the corners of a unit square.

Corner mapping: a = (0,0), b = (1,0), c = (0,1), d = (1,1).

Continuous channels are interpolated bilinearly — the sliders, plus both axes of an xypad, hrange or vrange. Discrete channels (button, checkbox, combobox) follow discreteMode .

Call this every frame (e.g. from CsoundUnityVectorMorph) to drive real-time vector synthesis.

Parameters
aPreset at corner (0,0).
bPreset at corner (1,0).
cPreset at corner (0,1).
dPreset at corner (1,1).
positionNormalised 2-D blend position, clamped to [0,1] on each axis.
discreteModeHow button/checkbox/combobox channels are resolved during the blend.

◆ ChannelsUpdated()

delegate void Csound.Unity.CsoundUnity.ChannelsUpdated ( )

The delegate of the event OnChannelsUpdated.

◆ ClearSpin()

void Csound.Unity.CsoundUnity.ClearSpin ( )
inline

Clears the input buffer (spin).

◆ CompiledWithoutError()

bool Csound.Unity.CsoundUnity.CompiledWithoutError ( )
inline

Returns true if the csd file was compiled without errors.

Returns
true when Csound compilation succeeded; otherwise false.

◆ CompileOrc()

int Csound.Unity.CsoundUnity.CompileOrc ( string orcStr)
inline

Parse, and compile the given orchestra from an ASCII string, also evaluating any global space code (i-time only) this can be called during performance to compile a new orchestra. This sample shows how to use CompileOrc.

string orc = "instr 1 \n a1 rand 0dbfs/4 \n out a1 \nendin\n";
int CompileOrc(string orcStr)
Parse, and compile the given orchestra from an ASCII string, also evaluating any global space code (i...
Definition CsoundUnity.Performance.cs:387
Parameters
orcStrThe orchestra string to compile.

After CsoundReset, compilation keeps audio suspended until CsoundStart is called explicitly.

Returns
Zero on success, or a non-zero Csound error code.

◆ ConvertPresetToScriptableObject()

void Csound.Unity.CsoundUnity.ConvertPresetToScriptableObject ( string path,
string destination )
inline

Convert a JSON preset into a Scriptable Object preset to be written at the specified path. If path is empty the converted preset will be saved inside the Assets folder.

Parameters
pathPath to the source JSON preset file.
destinationTarget directory inside the Assets folder where the ScriptableObject will be written.

◆ CopyChannelsToClipboard()

bool Csound.Unity.CsoundUnity.CopyChannelsToClipboard ( )
inline

Puts this instance's control channels on the system clipboard, as the same JSON a CsoundUnityPreset is saved in — so a clipboard snapshot and a saved .json preset are interchangeable, and channels can be pasted into a chat window as readily as back into an inspector.

For the quick pass a preset asset is too heavy for: try a change, dislike it, paste the old values back. Works in play mode.

Returns
true when something was copied.

◆ CopyFloatTableIn()

void Csound.Unity.CsoundUnity.CopyFloatTableIn ( int table,
float[] source )
inline

Same as CopyTableIn but passing a float array.

Parameters
tableThe function table number to write to.
sourceFloat array whose values will be copied into the table.

◆ CopyTableIn()

void Csound.Unity.CsoundUnity.CopyTableIn ( int table,
MYFLT[] source )
inline

Copy the contents of a supplied array into a function table The table number is assumed to be valid, and the destination needs to have sufficient space to receive all the function table contents.

Parameters
tablethe number of the table
sourcethe supplied array

◆ CopyTableInAsync() [1/2]

void Csound.Unity.CsoundUnity.CopyTableInAsync ( int table,
MYFLT[] source )
inline

Queues a snapshot of the source for a later performance cycle.

Parameters
tableThe function table number to write.
sourceThe samples to copy in. A snapshot is taken at submission.

◆ CopyTableInAsync() [2/2]

CsoundTableCopySubmission Csound.Unity.CsoundUnity.CopyTableInAsync ( int table,
MYFLT[] source,
out CsoundTableCopyRequest request )
inline

Queues a table write and returns a request to poll on the calling thread.

A null request means the write was not queued.

Parameters
tableThe function table number to write.
sourceThe samples to copy in. A snapshot is taken at submission.
requestThe request to poll, or null when the copy was not queued.
Returns
Whether the copy was queued, and why it was not.

◆ CopyTableOut()

void Csound.Unity.CsoundUnity.CopyTableOut ( int table,
out MYFLT[] dest )
inline

Copy the contents of a function table into a supplied array dest The table number is assumed to be valid, and the destination needs to have sufficient space to receive all the function table contents.

Parameters
tableThe function table number to read from.
destOutput array that receives the table contents.

◆ CopyTableOutAsync() [1/2]

void Csound.Unity.CsoundUnity.CopyTableOutAsync ( int table,
out MYFLT[] dest )
inline

Queues a read into an array filled during a later performance cycle.

Use the overload with a request to determine when the array is ready.

Parameters
tableThe function table number to read.
destThe array the copy will fill, sized for the table.

◆ CopyTableOutAsync() [2/2]

CsoundTableCopySubmission Csound.Unity.CsoundUnity.CopyTableOutAsync ( int table,
out MYFLT[] dest,
out CsoundTableCopyRequest request )
inline

Queues a table read and returns the destination and a request to poll on the calling thread.

A null request means the read was not queued. Only read the destination after CsoundTableCopyRequest.Succeeded is true.

Parameters
tableThe function table number to read.
destThe array the copy will fill, sized for the table.
requestThe request to poll, or null when the copy was not queued.
Returns
Whether the copy was queued, and why it was not.

◆ CreateFloatTable()

int Csound.Unity.CsoundUnity.CreateFloatTable ( int tableNumber,
float[] samples )
inline

Creates a table with the supplied float samples. Can be called during performance.

Parameters
tableNumberThe Csound function table number to create.
samplesFloat array of samples to populate the table with.
Returns
Zero on success, or -1 on failure.

◆ CreateInstance()

GeneratorInstance Csound.Unity.CsoundUnity.CreateInstance ( ControlContext context,
AudioFormat? nestedFormat = null,
ProcessorInstance.CreationParameters creationParameters = default )
inline

Called by Unity when AudioSource.generator = this is set (or when a scene with a serialized generator reference is loaded). Creates the unmanaged CsoundRealtime and CsoundControl structs and hands them to Unity via context.AllocateGenerator.

Parameters
contextThe control thread context Unity passes in.
nestedFormatThe format of a nested graph, or null for the output's own.
creationParametersWhat Unity asks the instance to be created with.
Returns
The generator instance Unity will drive.

◆ CreatePreset() [1/2]

CsoundUnityPreset Csound.Unity.CsoundUnity.CreatePreset ( string presetName,
string csoundFileName,
List< CsoundChannelController > channels )
inlinestatic

Create a CsoundUnityPreset from a presetName, csoundFileName and a list of CsoundChannelControllers.

Parameters
presetNameName of the preset (defaults to "CsoundUnityPreset" if empty).
csoundFileNameName of the CSD file this preset is associated with.
channelsChannel controllers whose values will be deep-copied into the preset.
Returns
A new CsoundUnityPreset ScriptableObject instance.

◆ CreatePreset() [2/2]

CsoundUnityPreset Csound.Unity.CsoundUnity.CreatePreset ( string presetName,
string presetData )
inlinestatic

Create a CsoundUnityPreset from a presetName and presetData.

PresetData should be a CsoundUnityPreset in the JSON format.

It will use the presetName parameter if not empty, if presetName is empty it will use preset.presetName, if also preset.presetName is empty it will use "CsoundUnityPreset" as a default name.

Parameters
presetNameName override; if empty the name embedded in presetData is used.
presetDataJSON string representing a CsoundUnityPreset.
Returns
The deserialized preset, or null if the JSON could not be parsed.

◆ CreateTable()

int Csound.Unity.CsoundUnity.CreateTable ( int tableNumber,
MYFLT[] samples )
inline

Creates a table with the supplied samples. Can be called during performance.

Parameters
tableNumberThe Csound function table number to create.
samplesMYFLT array of samples to populate the table with.
Returns
Zero on success, or -1 on failure.

◆ CreateTableInstrument()

int Csound.Unity.CsoundUnity.CreateTableInstrument ( int tableNumber,
int tableLength )
inline

Creates an empty table, to be filled with samples later. Please note that trying to read the samples from an empty folder will produce a crash. Can be called during performance.

Parameters
tableNumberThe number of the newly created table
tableLengthThe length of the table in samples
Returns
0 If the table could be created

AudioSettings.outputSampleRate

◆ CsdRequestsMidi()

bool Csound.Unity.CsoundUnity.CsdRequestsMidi ( string csd)
inlinestaticpackage

Whether a csd asks Csound for a MIDI device. Comments are stripped before looking: a line that merely mentions -M, as a comment explaining it does, is not an option.

Parameters
csdThe whole csd, as text.

◆ CsoundInitialized()

delegate void Csound.Unity.CsoundUnity.CsoundInitialized ( )

The delegate of the event OnCsoundInitialized.

◆ CsoundPerformanceFinishedDelegate()

delegate void Csound.Unity.CsoundUnity.CsoundPerformanceFinishedDelegate ( )

The delegate of the event OnCsoundPerformanceFinished.

◆ CsoundPerformKsmps()

delegate void Csound.Unity.CsoundUnity.CsoundPerformKsmps ( )

The delegate of the event OnCsoundPerformKsmps.

◆ CsoundReset()

bool Csound.Unity.CsoundUnity.CsoundReset ( )
inline

Returns the Csound instance to its pre-compilation state, keeping it alive and reusable: the orchestra and the control channels are gone afterwards. Compile again before performing, and set the channel values again. The engine settings are re-armed here, so the instance keeps the host sample rate, ksmps and audio IO it was created with.

Prefer Restart, which stops the audio path and builds a fresh instance: it is the path everything in the package takes, and the one the samples use. This is the lower-level door, for a scene that wants to keep the same instance and compile something else into it. To reuse this instance, wait for the new orchestra, compile it with CompileOrc, then call CsoundStart explicitly. Compilation alone does not resume audio. Send score events and set the channel values again. Register new named audio channels with AddAudioChannel(string); the new orchestra is not automatically parsed for them. Expect a gap between reset and the new performance. Unavailable on WebGL.

Returns
True when reset succeeded. False when the instance is unavailable or its audio callback could not be suspended safely. A refused reset preserves engine state, but waiting for a callback can silence audio for up to 200 ms.

◆ CsoundStart()

int Csound.Unity.CsoundUnity.CsoundStart ( )
inline

Starts the compiled orchestra after CsoundReset and enables performance. Call CompileOrc first. Starting an already running instance is a no-op.

Stop disposes the instance. Use Initialize or Restart after Stop, rather than CsoundStart.

Returns
Zero on success or when already running; nonzero on failure, when the instance is unavailable or uncompiled, or on WebGL.

◆ CsoundStopped()

delegate void Csound.Unity.CsoundUnity.CsoundStopped ( )

The delegate of the event OnCsoundStopped.

◆ Get0dbfs()

MYFLT Csound.Unity.CsoundUnity.Get0dbfs ( )
inline

Get the 0 dBFS amplitude reference value as set by the 0dbfs statement in the orchestra.

Returns
The 0 dBFS reference amplitude, or 0 if not initialized.

◆ GetArrayChannel() [1/2]

CsoundArrayChannelStatus Csound.Unity.CsoundUnity.GetArrayChannel ( string name,
MYFLT[] destination,
int[] sizes,
out CsoundArrayChannelInfo info )
inline

Copy numeric data and its axis sizes under one channel lock, including when producers resize.

Parameters
nameThe channel name.
destinationDestination for the whole current array.
sizesDestination for the current axis sizes.
infoMetadata corresponding to this copy, or required capacity on BufferTooSmall.
Returns
The copy result. Neither buffer is modified when a buffer is too small.

◆ GetArrayChannel() [2/2]

CsoundArrayChannelStatus Csound.Unity.CsoundUnity.GetArrayChannel ( string name,
MYFLT[] destination,
out int length )
inline

Copy a numeric array into a reusable flat buffer; unused trailing entries are unchanged.

Parameters
nameThe channel name.
destinationDestination for the whole current array.
lengthNumber of elements copied, or required when BufferTooSmall is returned.
Returns
The copy result. No channel is created and no partial copy is performed.

◆ GetArrayChannelInfo()

CsoundArrayChannelStatus Csound.Unity.CsoundUnity.GetArrayChannelInfo ( string name,
int[] sizes,
out CsoundArrayChannelInfo info )
inline

Read array metadata and axis sizes without creating a channel or allocating a buffer.

Parameters
nameThe channel name.
sizesDestination for axis sizes; unused trailing entries are unchanged.
infoCurrent metadata, also returned when a supplied buffer is too small.
Returns
The read result; UnsupportedPlatform in WebGL players.

◆ GetAudioArrayChannel() [1/2]

CsoundArrayChannelStatus Csound.Unity.CsoundUnity.GetAudioArrayChannel ( string name,
MYFLT[] destination,
int[] sizes,
out CsoundArrayChannelInfo info )
inline

Copy audio blocks and their axis sizes under one channel lock, including when producers resize.

Parameters
nameThe channel name.
destinationDestination for ElementCount × ksmps samples.
sizesDestination for the current axis sizes.
infoMetadata corresponding to this copy, or required capacity on BufferTooSmall.
Returns
The copy result. Neither buffer is modified when a buffer is too small.

◆ GetAudioArrayChannel() [2/2]

CsoundArrayChannelStatus Csound.Unity.CsoundUnity.GetAudioArrayChannel ( string name,
MYFLT[] destination,
out int length )
inline

Copy an audio array into a reusable flat buffer; unused trailing entries are unchanged.

Parameters
nameThe channel name.
destinationDestination for ElementCount × ksmps samples.
lengthNumber of samples copied, or required when BufferTooSmall is returned.
Returns
The copy result. No channel is created and no partial copy is performed.

◆ GetAudioChannel() [1/2]

MYFLT[] Csound.Unity.CsoundUnity.GetAudioChannel ( string channel)
inline

Gets a Csound Audio channel. Used in connection with a chnset opcode in your Csound instrument.

Parameters
channelName of the Csound audio channel to read.
Returns
An array of ksmps audio samples, or null if not initialized.

◆ GetAudioChannel() [2/2]

void Csound.Unity.CsoundUnity.GetAudioChannel ( string channel,
MYFLT[] dest )
inline

Zero-allocation overload: reads the named audio channel directly into dest without any managed or native heap allocation. Prefer this on hot audio-thread paths (e.g. inside OnAudioFilterRead or a ksmps callback) to avoid GC pressure and the periodic audio dropouts it causes.

Parameters
channelName of the Csound audio channel to read.
destPre-allocated destination array (at least ksmps long). Null or empty arrays are ignored.
Exceptions
ArgumentExceptionA non-empty destination is shorter than ksmps.

◆ GetAudioChannelReader()

AudioChannelReader Csound.Unity.CsoundUnity.GetAudioChannelReader ( string channelName)
inline

Returns a reader for the audio this instance publishes on a named audio channel: one finished block at a time, readable from any thread.

Parameters
channelNameA channel the CSD writes with chnset, or one of the automatic output channels main_out_0, main_out_1, …
Returns
A reader, or null for an empty name. Call it once and keep the reader: each one carries its own position in the stream, so two readers on the same channel both receive every block.

This is the supported way to take audio out of a channel. Reading namedAudioChannelDataDict instead reaches the live working array, which another thread may be half-way through writing.

◆ GetAudioChannelSample()

double Csound.Unity.CsoundUnity.GetAudioChannelSample ( string channel,
int sample )
inline

Returns a sample from a CsoundUnity audio channel This is useful if you want to update an AudioSource using the OnAudioFilterRead callback Internally it uses the namedAudioChannelDataDict buffer, that is usually used to update CsoundUnityChild scripts Using this together with AddAudioChannel(string) and RemoveAudioChannel(string) allows you to create new audio channels at runtime.

Parameters
channelAn existing audio channel buffer
sampleZero-based sample index within the channel buffer.
Returns
The sample value at sample , or 0 if the channel or index is invalid.

Reads the live working buffer, which the audio thread is writing into. Called from the main thread it may therefore return a sample from a block that is only half produced, and it will keep returning the last block written if the instance stops updating it (muted, paused, or finished). Fine for metering and visualisation, where an occasional wrong sample does not matter; not a safe way to move audio between instances. Use GetAudioChannelReader, which delivers finished blocks and is what audio input routing and CsoundUnityChild read.

◆ GetChannel() [1/2]

MYFLT Csound.Unity.CsoundUnity.GetChannel ( string channel)
inline

Gets a Csound channel. Used in connection with a chnset opcode in your Csound instrument, or set with SetChannel.

Parameters
channelName of the Csound channel to read.
Returns
The current numeric value of the channel, or 0 if not initialized.

◆ GetChannel() [2/2]

void Csound.Unity.CsoundUnity.GetChannel ( string channel,
Action< MYFLT > callback )
inline

Reads a Csound control channel and delivers the result via callback . On non-WebGL platforms the callback is invoked synchronously before this method returns. On WebGL the read is dispatched to the AudioWorklet thread; the callback fires on the main thread once the value is available (typically within the same or the next frame).

Parameters
channelName of the control channel to read.
callbackCalled with the value.

◆ GetChannelController()

CsoundChannelController Csound.Unity.CsoundUnity.GetChannelController ( string channel)
inline

Returns the serialized CsoundChannelController for the named channel, as parsed from the CSD file by ParseCsdFile.

Parameters
channelThe channel name to look up.
Returns
The matching controller, or null if not found.

◆ GetChannelList()

IDictionary< string, CsoundUnityBridge.ChannelInfo > Csound.Unity.CsoundUnity.GetChannelList ( )
inline

Blocking method to get a list of the channels from Csound, not from the serialized list of this instance. Provides a dictionary of all currently defined channels resulting from compilation of an orchestra containing channel definitions. Entries, keyed by name, are polymorphically assigned to their correct data type: control, audio, string, pvc.

Returns
A dictionary of all currently defined channels keyed by their name to its ChannelInfo, or null if not initialized.

◆ GetCurrentTimeSamples()

long Csound.Unity.CsoundUnity.GetCurrentTimeSamples ( )
inline

Returns the current performance time in samples.

Returns
Total number of audio samples rendered since performance began.

◆ GetEnv()

string Csound.Unity.CsoundUnity.GetEnv ( EnvType envType)
inline

Get Environment path.

Parameters
envTypethe type of the environment to get
Returns
the corresponding value or an empty string if no such key exists

◆ GetKr()

MYFLT Csound.Unity.CsoundUnity.GetKr ( )
inline

Get the current control rate.

Returns
The Csound control rate (kr) in Hz.

◆ GetKsmps()

uint Csound.Unity.CsoundUnity.GetKsmps ( )
inline

Get the number of audio sample frames per control sample.

Returns
The ksmps value currently used by Csound.

◆ GetNchnls()

uint Csound.Unity.CsoundUnity.GetNchnls ( )
inline

Get the number of output channels.

Returns
The value of Csound's nchnls, or 0 if not initialized.

◆ GetNchnlsInputs()

uint Csound.Unity.CsoundUnity.GetNchnlsInputs ( )
inline

Get the number of input channels.

Returns
The value of Csound's nchnls_i, or 0 if not initialized.

◆ GetOutputSample()

MYFLT Csound.Unity.CsoundUnity.GetOutputSample ( int frame,
int channel )
inline

Get a sample from Csound's audio output buffer.

Parameters
frameFrame index within the current ksmps block (0-based).
channelOutput channel index (0-based).
Returns
The sample value at the given frame and channel.

◆ GetPublishedAudioChannel()

CsoundSharedBuffer Csound.Unity.CsoundUnity.GetPublishedAudioChannel ( string channelName)
inlinepackage

Returns the published snapshot buffer for channelName , or null if this instance has never published that channel.

◆ GetPvsChannel()

CsoundPvsChannelStatus Csound.Unity.CsoundUnity.GetPvsChannel ( string name,
float[] destination,
out CsoundPvsChannelInfo info )
inline

Read a complete N+2 float frame and matching metadata; neither partial copies nor channel creation occur.

Parameters
nameThe channel name.
destinationReusable float buffer, independent of native audio precision; unused tails are unchanged.
infoMatching metadata, also returned on BufferTooSmall so FrameLength reports required capacity.
Returns
The read result; the buffer is unchanged on BufferTooSmall. UnsupportedPlatform in WebGL.

◆ GetPvsChannelInfo()

CsoundPvsChannelStatus Csound.Unity.CsoundUnity.GetPvsChannelInfo ( string name,
out CsoundPvsChannelInfo info )
inline

Read PVS layout and frame counter without creating a channel.

Parameters
nameThe channel name.
infoCurrent FFT/hop/window/format and frame counter.
Returns
The metadata result; UnsupportedPlatform in WebGL players.

◆ GetSpin()

MYFLT[] Csound.Unity.CsoundUnity.GetSpin ( )
inline

Get Csound's audio input buffer.

Returns
The raw spin (input) buffer array, or null if not initialized.

◆ GetSpout()

MYFLT[] Csound.Unity.CsoundUnity.GetSpout ( )
inline

Get Csound's audio output buffer.

Returns
The raw spout (output) buffer array, or null if not initialized.

◆ GetSr()

MYFLT Csound.Unity.CsoundUnity.GetSr ( )
inline

Get the current sample rate.

Returns
The Csound sample rate (sr) in Hz.

◆ GetStringArrayChannel() [1/2]

CsoundArrayChannelStatus Csound.Unity.CsoundUnity.GetStringArrayChannel ( string name,
string[] destination,
int[] sizes,
out CsoundArrayChannelInfo info )
inline

Read UTF-8 string values and their matching shape atomically; decode outside the native spin lock.

Parameters
nameThe channel name.
destinationDestination for all current string elements.
sizesDestination for current axis sizes.
infoMetadata corresponding to the snapshot, or required capacity on BufferTooSmall.
Returns
The read result; neither buffer changes on BufferTooSmall.

◆ GetStringArrayChannel() [2/2]

CsoundArrayChannelStatus Csound.Unity.CsoundUnity.GetStringArrayChannel ( string name,
string[] destination,
out int length )
inline

Read a complete string array into a reusable container. Changed strings allocate; unchanged values retain their references. Runs outside audio callbacks and does not create a channel.

Parameters
nameThe channel name.
destinationDestination for all current elements; unused trailing entries are unchanged.
lengthElements copied, or required capacity on BufferTooSmall.
Returns
The read result; UnsupportedPlatform in WebGL, Busy in an audio callback.

◆ GetStringChannel()

string Csound.Unity.CsoundUnity.GetStringChannel ( string name)
inline

Get a Csound string channel. Used in connection with a chnset opcode in your Csound instrument, or set with SetStringChannel.

Parameters
nameName of the Csound string channel to read.
Returns
The current value, or null if the component is not initialized. An initialized component returns an empty string if the read is unavailable, including on WebGL or while another operation holds the bridge's channel gate.

◆ GetTable()

int Csound.Unity.CsoundUnity.GetTable ( out MYFLT[] tableValues,
int numTable )
inline

Stores values to function table 'numTable' in tableValues, and returns the table length (not including the guard point). If the table does not exist, tableValues is set to NULL and -1 is returned.

Parameters
tableValuesOutput array filled with the table contents.
numTableThe function table number to read.
Returns
The table length, or -1 if the table does not exist.

◆ GetTableArgs()

int Csound.Unity.CsoundUnity.GetTableArgs ( out MYFLT[] args,
int index )
inline

Stores the arguments used to generate function table 'tableNum' in args, and returns the number of arguments used. If the table does not exist, args is set to NULL and -1 is returned. NB: 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}.

Parameters
argsOutput array filled with the GEN number followed by its parameters.
indexThe function table number to query.
Returns
The number of generation arguments, or -1 if the table does not exist.

◆ GetTableLength()

int Csound.Unity.CsoundUnity.GetTableLength ( int table)
inline

Returns the length of a function table (not including the guard point), or -1 if the table does not exist.

Parameters
tableThe function table number to query.
Returns
The table length (excluding guard point), or -1 if the table does not exist.

◆ GetTableSample()

MYFLT Csound.Unity.CsoundUnity.GetTableSample ( int tableNumber,
int index )
inline

Retrieves a single sample from a Csound function table.

Parameters
tableNumberThe function table number.
indexZero-based sample index within the table.
Returns
The sample value at the given index, or 0 if not initialized.

◆ GetVersion()

int Csound.Unity.CsoundUnity.GetVersion ( )
inline

Returns the Csound version number times 1000 (5.00.0 = 5000).

Returns
The Csound version as an integer (e.g. 6070 for version 6.07.0).

◆ Initialize()

void Csound.Unity.CsoundUnity.Initialize ( )
inline

Initializes CsoundUnity manually. Only works if initializeOnAwake is false, or after a Stop. Silently returns if already initialized or initializing.

◆ InitializeArrayChannel()

CsoundArrayChannelStatus Csound.Unity.CsoundUnity.InitializeArrayChannel ( string name,
CsoundArrayChannelType type,
params int[] sizes )
inline

Create an i[], k[], S[] or a[] channel, or verify an existing channel's exact type and shape. Initialization may allocate and briefly suspend Unity audio processing; call during setup, never from an audio callback. Existing channels are not resized.

Parameters
nameThe channel name.
typeInit, Control, String or Audio elements.
sizesOne nonnegative size per axis.
Returns
The initialization or shape-validation result; UnsupportedPlatform in WebGL players.

◆ InitializePvsChannel()

CsoundPvsChannelStatus Csound.Unity.CsoundUnity.InitializePvsChannel ( string name,
int fftSize,
int overlap,
int windowSize,
int windowType = 1,
CsoundPvsFormat format = CsoundPvsFormat::AmplitudeFrequency )
inline

Create or verify a fixed-layout PVS channel during setup. May allocate and briefly suspend Unity audio.

Parameters
nameA nonempty UTF-8 channel name.
fftSizeEven FFT size N.
overlapAnalysis hop in audio samples; at least global ksmps and greater than 10.
windowSizeAnalysis window size in samples.
windowTypeBuilt-in Csound window code (0-9); defaults to Hann.
formatMeaning of each float pair.
Returns
The creation/validation result; Busy in an audio callback, UnsupportedPlatform in WebGL.

◆ IsButtonChannel()

bool Csound.Unity.CsoundUnity.IsButtonChannel ( CsoundChannelController ch)
inlinestaticpackage

A button channel carries an impulse, not a state: the csd zeroes it with its own chnset, which the serialised copy never sees, so a click leaves 1 in the list for good. Everything that pours serialised values back into Csound skips these. A checkbox is excluded: that one does hold a state worth restoring.

Parameters
chThe channel controller to test.
Returns
true for a button-type channel.

◆ IsRestorable()

bool Csound.Unity.CsoundUnity.IsRestorable ( CsoundChannelController ch)
inlinestaticpackage

Whether the clipboard can carry and restore this channel. It needs a name — the csd's form, and any widget without one, is in the list but is not a channel — and a button is excluded because a momentary trigger has no value worth putting back.

Copy and paste share this so the two report the same number, instead of one counting controllers and the other counting what it managed to apply.

◆ LoadCsdFromPath() [1/2]

void Csound.Unity.CsoundUnity.LoadCsdFromPath ( string path,
Action< bool > onLoaded,
bool startNow = true )
inline

Reads a CSD with UnityWebRequest and loads it, then reports the outcome to onLoaded . Works for the cases the synchronous overload refuses: StreamingAssets on any platform, and http/https URLs.

The component must be active and enabled, since the read runs as a coroutine.

Parameters
pathPath or URL to the .csd file.
onLoadedCalled with true when Csound ends up running the CSD, false when the read failed, the CSD did not compile, or startNow is false.
startNowPassed through to LoadCsdFromString.

◆ LoadCsdFromPath() [2/2]

bool Csound.Unity.CsoundUnity.LoadCsdFromPath ( string path,
bool startNow = true )
inline

Reads a CSD from a file and loads it, the runtime counterpart of assigning a csd asset. Equivalent to reading the file yourself and calling LoadCsdFromString.

Use this for real filesystem paths — Application.persistentDataPath, an absolute path, anything the user picked. For a URL, or for StreamingAssets on Android and WebGL where the folder lives inside the compressed application package and cannot be read as a file, use the overload that takes a callback: this one refuses with an explicit error rather than failing quietly.

Parameters
pathPath to the .csd file.
startNowPassed through to LoadCsdFromString.
Returns
true when Csound is running the CSD from the file by the time this returns. false when the file could not be read, when it did not compile, or when startNow is false. Every case logs its reason.

◆ LoadCsdFromString()

bool Csound.Unity.CsoundUnity.LoadCsdFromString ( string csdContent,
bool startNow = true )
inline

Loads a CSD from a raw string at runtime, without requiring a .csd asset.

This is the runtime counterpart of SetCsd (which is editor-only and works via an asset GUID). Use it for dynamically generated or downloaded CSDs. The Csound bridge compiles directly from the stored string, so no file is needed.

Channel controllers, named audio channels, nchnls and ksmps are parsed from the string exactly as SetCsd parses them from a file.

Startup behaviour when startNow is true:

  • Already running — the instance is reloaded via Restart.
  • Not running — started now via Initialize, whatever initializeOnAwake says: once Awake has run it will not run again, so there is nobody else left to compile the string.

If Awake has not run yet (audioSource not resolved), only the fields are populated; initialization is deferred to Awake or a later Initialize call, because Init depends on Awake-time state (DSP buffer size, AudioSource).

Parameters
csdContentThe full CSD text to load.
startNowWhen true, (re)initialize Csound after loading; when false, only store and parse the CSD (call Initialize yourself).
Returns
true when Csound is running the new CSD by the time this returns. false otherwise, which is not always a failure: it is also what you get when startNow is false, or when Awake has not run yet and the CSD was only stored. A compile error also lands here, and is logged.

◆ LoadGlobalPreset()

void Csound.Unity.CsoundUnity.LoadGlobalPreset ( string path)
inline

Load a global preset on this CsoundUnity instance from a JSON file found at path. The JSON file should represent a Global Preset, ie a complete CsoundUnity instance.

This also sets the global preset, overriding the current content of this CsoundUnity instance.

This could have unintended consequences in certain situations. You could need to disable this CsoundUnity GameObject and enable it again to restore the Csound internal state.

Parameters
pathThe path must point to an existing JSON file

◆ LoadPlugins()

int Csound.Unity.CsoundUnity.LoadPlugins ( string dir)
inline

Loads all plugins from a given directory.

Parameters
dirPath to the directory containing Csound plugin libraries.
Returns
Zero on success, or a non-zero error code.

◆ LoadPreset()

void Csound.Unity.CsoundUnity.LoadPreset ( string path,
Action< CsoundUnityPreset > onPresetLoaded = null )
inline

Loads a preset from a JSON file. The JSON file should represent a CsoundUnityPreset.

This doesn't set the preset.

You should use the Action to get the reference of the loaded preset. This is needed because of the async nature of this method, that uses a WebRequest on Android and iOS.

Example of usage:

LoadPreset("myPath/presetName.json", (loadedPreset) =>
{
SetPreset(loadedPreset);
});
CsoundUnityPreset SetPreset(string presetName, string presetData)
Set a CsoundUnityPreset to this CsoundUnity instance using a presetName and presetData....
Definition CsoundUnity.Presets.cs:344
void LoadPreset(string path, Action< CsoundUnityPreset > onPresetLoaded=null)
Loads a preset from a JSON file. The JSON file should represent a CsoundUnityPreset.
Definition CsoundUnity.Presets.cs:493
Parameters
pathThe path must point to an existing JSON file
onPresetLoadedCalled with the loaded preset, or with null when the file could not be read.

◆ MorphToPreset()

Coroutine Csound.Unity.CsoundUnity.MorphToPreset ( CsoundUnityPreset preset,
float duration,
AnimationCurve curve = null,
Action onComplete = null,
DiscreteChannelMode discreteMode = DiscreteChannelMode::SnapAtEnd )
inline

Smoothly interpolates all continuous channels — the sliders, plus both axes of an xypad, hrange or vrange — from their current values to the target preset's values over the given duration. An optional AnimationCurve controls easing; pass null for linear interpolation. The returned Coroutine can be passed to StopMorph to cancel mid-way. If duration is zero or negative, the preset is applied immediately.

Parameters
presetThe target preset to morph towards.
durationDuration of the morph in seconds. Zero or negative applies the preset instantly.
curveOptional easing curve evaluated over [0,1]; null = linear.
onCompleteOptional callback invoked when the morph finishes.
discreteModeControls when button/checkbox/combobox channels are snapped to their target values.
Returns
The running Coroutine, or null when the preset was applied instantly.

◆ NotifyChannelsUpdated()

void Csound.Unity.CsoundUnity.NotifyChannelsUpdated ( )
inline

Raises OnChannelsUpdated. Call it after writing several channels yourself with SetChannel(string, MYFLT), so the UI components re-read them.

Applying a preset or pasting channels does this already. It is a separate call rather than something SetChannel does on its own because a single write happens on every frame a slider moves, and firing there would have every widget re-read on every frame.

◆ ParseCsdFile()

List< CsoundChannelController > Csound.Unity.CsoundUnity.ParseCsdFile ( string filename)
inlinestatic

Parses the CSD file's Cabbage widget section and returns a list of CsoundChannelController objects describing every slider, button, checkbox, combobox, xypad, and similar widget found.

Parameters
filenameFull path to the CSD file.
Returns
A list of parsed channel controllers, or null if the file does not exist or is empty.

◆ ParseCsdFileForAudioChannels()

List< string > Csound.Unity.CsoundUnity.ParseCsdFileForAudioChannels ( string filename)
inlinestatic

Parses the CSD file and returns the names of all audio-rate channels declared via chnset avar, "channel name" (channels driven by a- or ga-rate variables with literal string names).

Parameters
filenameFull path to the CSD file.
Returns
A list of audio channel name strings, or null if the file does not exist or is empty.

◆ ParseCsdFileForKsmps()

int Csound.Unity.CsoundUnity.ParseCsdFileForKsmps ( string filename)
inlinestatic

Parses ksmps from the global header of the CSD's <CsInstruments> section. Returns the explicit ksmps value if declared; otherwise computes round(sr / kr) if both are present; otherwise returns 0 (not specified). Only scans lines before the first instr declaration.

Parameters
filenameFull path to the CSD file.
Returns
The resolved ksmps value, or 0 if it cannot be determined.

◆ ParseCsdFileForNchnls()

int Csound.Unity.CsoundUnity.ParseCsdFileForNchnls ( string filename)
inlinestatic

Reads the CSD file and returns the value of nchnls (output channels) declared in the orchestra header. Correctly ignores nchnls_i (input channels). Returns 0 when the directive is absent — in that case Csound defaults to 1, but callers should treat 0 as "unknown / not specified".

Parameters
filenameFull path to the CSD file.
Returns
The declared nchnls value, or 0 if not found.

◆ ParseCsdString()

List< CsoundChannelController > Csound.Unity.CsoundUnity.ParseCsdString ( string csdContent)
inlinestatic

String equivalent of ParseCsdFile — parses the Cabbage widget section from CSD text already in memory (no file path), e.g. from LoadCsdFromString.

Parameters
csdContentThe full CSD text.
Returns
A list of parsed channel controllers, or null if the content is empty.

◆ ParseCsdStringForAudioChannels()

List< string > Csound.Unity.CsoundUnity.ParseCsdStringForAudioChannels ( string csdContent)
inlinestatic

Parses a CSD string (already in memory) for named audio channels written with chnset. Runtime equivalent of ParseCsdFileForAudioChannels used when only the CSD content is available (no file path), e.g. during Init on first play after a fresh package import where the inspector was never opened to trigger SetCsd.

Parameters
csdContentThe full CSD text.
Returns
Unique scalar audio channel names, including indexed array elements but excluding whole arrays; never null.

◆ ParseCsdStringForKsmps()

int Csound.Unity.CsoundUnity.ParseCsdStringForKsmps ( string csdContent)
inlinestatic

String equivalent of ParseCsdFileForKsmps, used when only the CSD content is available (no file path), e.g. from LoadCsdFromString.

Parameters
csdContentThe full CSD text.
Returns
The resolved ksmps value, or 0 if it cannot be determined.

◆ ParseCsdStringForNchnls()

int Csound.Unity.CsoundUnity.ParseCsdStringForNchnls ( string csdContent)
inlinestatic

String equivalent of ParseCsdFileForNchnls, used when only the CSD content is available (no file path), e.g. from LoadCsdFromString.

Parameters
csdContentThe full CSD text.
Returns
The declared nchnls value, or 0 if not found.

◆ ParseCsdStringForUnsupportedWidgets()

List< string > Csound.Unity.CsoundUnity.ParseCsdStringForUnsupportedWidgets ( string csdContent)
inlinestatic

Cabbage widget names that appear in a csd but that the parser does not build a channel for, so the inspector and the UI generator can say so instead of silently showing less than the csd declares.

A line counts as a widget when it carries a bounds( attribute. keyboard is deliberately not reported: CsoundUnityKeyboard exists, it is simply built in the scene rather than read from the csd.

Parameters
csdContentThe full CSD text.
Returns
The distinct unsupported widget names, in the order they appear.

◆ ParseSnap()

List< CsoundUnityPreset > Csound.Unity.CsoundUnity.ParseSnap ( string csdPath,
string snapPath )
inlinestatic

Parses a Cabbage .snaps file and returns a list of CsoundUnityPreset objects, one per snapshot entry, with channel metadata filled in from the companion CSD.

Parameters
csdPathFull path to the CSD file used as the reference for channel types and ranges.
snapPathFull path to the Cabbage .snaps file to parse.
Returns
A list of presets parsed from the snap file.
Exceptions
FormatExceptionA channel entry has an invalid numeric value.

◆ PasteChannelsFromClipboard()

bool Csound.Unity.CsoundUnity.PasteChannelsFromClipboard ( )
inline

Applies channels held on the clipboard in the CsoundUnityPreset JSON format.

Unlike SetPreset(CsoundUnityPreset) this does not refuse when the clipboard came from another csd. Refusing would defeat the purpose — the clipboard is for moving values by hand, between instances and between csds that share channel names — so the channels this csd declares are applied and the rest are reported.

Returns
true when at least one channel was applied.

◆ PerformKsmps()

int Csound.Unity.CsoundUnity.PerformKsmps ( )
inline

Process a ksmps-sized block of samples.

Returns
Zero while the performance continues, a positive value when the score has ended, or CsoundUnityBridge.DestroyedSentinel if the instance has been freed. Test for score end with > 0, not != 0.

◆ RemoveAllAudioInputRoutes()

void Csound.Unity.CsoundUnity.RemoveAllAudioInputRoutes ( )
inline

Removes all audio input routes from this instance.

◆ RemoveAudioChannel()

void Csound.Unity.CsoundUnity.RemoveAudioChannel ( string channel)
inline

Removes an audio channel from the list that can be used in CsoundUnityChild.

Parameters
channelThe channel to be removed

◆ RemoveAudioInputRoute() [1/3]

void Csound.Unity.CsoundUnity.RemoveAudioInputRoute ( CsoundUnity source)
inline

Removes all audio input routes whose source is source .

Parameters
sourceThe instance whose routes into this one are removed.

◆ RemoveAudioInputRoute() [2/3]

void Csound.Unity.CsoundUnity.RemoveAudioInputRoute ( CsoundUnity source,
string sourceChannelName,
int destSpinChannel )
inline

Removes the specific audio input route that matches all three key fields.

Parameters
sourceThe instance the route comes from.
sourceChannelNameThe named audio channel the route reads.
destSpinChannelThe spin channel the route writes into.

◆ RemoveAudioInputRoute() [3/3]

void Csound.Unity.CsoundUnity.RemoveAudioInputRoute ( int index)
inline

Removes the audio input route at index in audioInputRoutes.

Parameters
indexIndex of the route in audioInputRoutes.

◆ ResetDspLoadStatistics()

void Csound.Unity.CsoundUnity.ResetDspLoadStatistics ( )
inline

Requests a statistics reset at the next measured DSP block. Call from the main thread. Measurement must be enabled for the reset to take effect.

◆ Restart()

void Csound.Unity.CsoundUnity.Restart ( )
inline

Stops the current Csound instance and reinitializes it from scratch.

◆ RewindScore()

void Csound.Unity.CsoundUnity.RewindScore ( )
inline

Rewinds a compiled Csound score to the time specified with SetScoreOffsetSeconds().

◆ SaveGlobalPreset()

void Csound.Unity.CsoundUnity.SaveGlobalPreset ( string presetName,
string path = null,
bool overwriteIfExisting = false )
inline

Save a serialized copy of this CsoundUnity instance. Similar behaviour as saving a Unity Preset from the inspector of the CsoundUnity component, but this can be used at runtime.

Parameters
presetNameName for the global preset file.
pathTarget directory; defaults to Application.persistentDataPath if null.
overwriteIfExistingWhen false, a counter suffix is appended to avoid overwriting existing files.

◆ SavePresetAsJSON() [1/3]

void Csound.Unity.CsoundUnity.SavePresetAsJSON ( CsoundUnityPreset preset,
string path = null,
bool overwriteIfExisting = false )
inlinestatic

Save the specified CsoundUnityPreset as JSON, at the specified path. If a file exists at the specified path, it will be overwritten if overwriteIfExisting is true.

Parameters
presetThe preset to serialize to JSON.
pathTarget directory path; defaults to Application.persistentDataPath if null.
overwriteIfExistingWhen false, a counter suffix is appended to avoid overwriting existing files.

◆ SavePresetAsJSON() [2/3]

void Csound.Unity.CsoundUnity.SavePresetAsJSON ( List< CsoundChannelController > channels,
string csoundFileName,
string presetName,
string path = null,
bool overwriteIfExisting = false )
inlinestatic

Save a preset as JSON from a list of CsoundChannelController, specifying the related CsoundFileName and the presetName. See SavePresetAsJSON(CsoundUnityPreset, string, bool).

Parameters
channelsChannel controllers to store in the preset.
csoundFileNameName of the CSD file this preset is associated with.
presetNameName for the preset.
pathTarget directory; defaults to Application.persistentDataPath if null.
overwriteIfExistingWhen false, a counter suffix is appended to avoid overwriting existing files.

◆ SavePresetAsJSON() [3/3]

void Csound.Unity.CsoundUnity.SavePresetAsJSON ( string presetName,
string path = null,
bool overwriteIfExisting = false )
inline

Save a preset as JSON using CsoundChannelControllers and CsoundFileName from this CsoundUnity instance. See SavePresetAsJSON(CsoundUnityPreset, string, bool).

Parameters
presetNameName for the preset.
pathTarget directory; defaults to Application.persistentDataPath if null.
overwriteIfExistingWhen false, a counter suffix is appended to avoid overwriting existing files.

◆ SavePresetAsScriptableObject()

void Csound.Unity.CsoundUnity.SavePresetAsScriptableObject ( string presetName,
string path = null )
inline

Save a CsoundUnityPreset of this CsoundUnity instance at the specified path, using the specified presetName. The current csoundFileName and list of CsoundChannelControllers will be saved in the preset. If no presetName is given, a default one will be used.

Parameters
presetNameName for the preset (defaults to "CsoundUnityPreset" if empty).
pathTarget directory path inside the Assets folder; defaults to Assets root if null.

◆ SendMidiControlChange()

void Csound.Unity.CsoundUnity.SendMidiControlChange ( int channel,
int controller,
int value )
inline

Sends a MIDI Control Change message to Csound.

Parameters
channelMIDI channel, 1–16
controllerController number, 0–127
valueController value, 0–127

◆ SendMidiMessage()

void Csound.Unity.CsoundUnity.SendMidiMessage ( byte[] data)
inline

Sends a raw MIDI message (1–3 bytes) directly to Csound. Use this for any MIDI message type not covered by the helper methods above.

Parameters
dataRaw MIDI bytes (1–3)

◆ SendMidiNoteOff()

void Csound.Unity.CsoundUnity.SendMidiNoteOff ( int channel,
int note,
int velocity = 0 )
inline

Sends a MIDI Note Off message to Csound.

Parameters
channelMIDI channel, 1–16
noteNote number, 0–127
velocityRelease velocity, 0–127 (usually 0)

◆ SendMidiNoteOn()

void Csound.Unity.CsoundUnity.SendMidiNoteOn ( int channel,
int note,
int velocity )
inline

Sends a MIDI Note On message to Csound. The CSD must have a MIDI device option (e.g. <CsOptions> -M0 </CsOptions>) for Csound to process MIDI events.

Parameters
channelMIDI channel, 1–16
noteNote number, 0–127
velocityVelocity, 0–127. Velocity 0 is treated as Note Off by convention.

◆ SendMidiProgramChange()

void Csound.Unity.CsoundUnity.SendMidiProgramChange ( int channel,
int program )
inline

Sends a MIDI Program Change message to Csound.

Parameters
channelMIDI channel, 1–16
programProgram number, 0–127

◆ SendScoreEvent()

void Csound.Unity.CsoundUnity.SendScoreEvent ( string scoreEvent)
inline

Send a score event to Csound in the form of "i1 0 10 ....

Parameters
scoreEventthe score string to send

◆ SetArrayChannel()

CsoundArrayChannelStatus Csound.Unity.CsoundUnity.SetArrayChannel ( string name,
MYFLT[] source )
inline

Replace all numeric elements of the channel's current shape; source length must match exactly.

Parameters
nameThe channel name.
sourceFlat i[] or k[] values, in Csound array order.
Returns
The write result. No channel is created or resized and no partial write is performed.

◆ SetAudioArrayChannel()

CsoundArrayChannelStatus Csound.Unity.CsoundUnity.SetAudioArrayChannel ( string name,
MYFLT[] source )
inline

Replace all audio samples of the channel's current shape; source length must match exactly.

Parameters
nameThe channel name.
sourceFlat a[] blocks: all ksmps samples of element 0, then element 1, and so on.
Returns
The write result. No channel is created or resized and no partial write is performed.

◆ SetChannel() [1/2]

void Csound.Unity.CsoundUnity.SetChannel ( CsoundChannelController channelController)
inline

Sets a Csound channel. Useful for setting presets at runtime. Used in connection with a chnget opcode in your Csound instrument.

Only the value is taken from channelController . The widget definition — type, range, skew, increment, options, bounds — belongs to the csd.

Parameters
channelControllerThe channel controller to take the value from.

◆ SetChannel() [2/2]

void Csound.Unity.CsoundUnity.SetChannel ( string channel,
MYFLT val )
inline

Sets a Csound channel. Used in connection with a chnget opcode in your Csound instrument.

val is the value as Csound holds it, so a combobox takes the 1-based Cabbage index. The serialized channel is updated through CsoundChannelController.SetFromCsoundValue.

Parameters
channelName of the Csound channel.
valValue to assign to the channel, in Csound's terms.

◆ SetChannels()

void Csound.Unity.CsoundUnity.SetChannels ( List< CsoundChannelController > channelControllers,
bool excludeButtons = true )
inline

Sets a list of Csound channels.

Parameters
channelControllersThe list of channel controllers to apply.
excludeButtonsWhen true (default), button-type channels are skipped.

◆ SetCsd()

void Csound.Unity.CsoundUnity.SetCsd ( string guid)
inline

Sets the CSD from a project asset, identified by its AssetDatabase GUID.

Editor only, and inherently so: a GUID is an AssetDatabase concept and there is no AssetDatabase in a build. The runtime equivalent is LoadCsdFromString(string, bool) — read the CSD text however suits the platform (a TextAsset, StreamingAssets, the network) and hand it the string.

Parameters
guidthe guid of the csd file asset

◆ SetGlobalEnv()

int Csound.Unity.CsoundUnity.SetGlobalEnv ( string name,
string value )
inline

Set the global value of environment variable 'name' to 'value', or delete variable if 'value' is NULL. It is not safe to call this function while any Csound instances are active. See https://csound.com/docs/manual/CommandEnvironment.html for a list of the variables that can be used.

Parameters
nameThe name of the environment variable to set
valueThe value to set, ie a path
Returns
Returns zero on success.

◆ SetGlobalPreset()

CsoundUnity Csound.Unity.CsoundUnity.SetGlobalPreset ( string presetName,
string presetData )
inline

Set a global preset to this CsoundUnity instance using a presetName and presetData.

Preset data should represent a CsoundUnity instance in JSON format.

This overrides the current content of this CsoundUnity instance.

This could have unintended consequences in certain situations. You could need to disable this CsoundUnity GameObject and enable it again to restore the Csound internal state.

This updated CsoundUnity instance will be returned.

Parameters
presetNameName to assign (overrides the name embedded in the JSON).
presetDataJSON string of a full CsoundUnity instance serialization.
Returns
This CsoundUnity instance (for method chaining).

◆ SetInputSample()

void Csound.Unity.CsoundUnity.SetInputSample ( int frame,
int channel,
MYFLT sample )
inline

Set a sample in Csound's input buffer, overwriting any existing value.

Parameters
frameFrame index within the current ksmps block (0-based).
channelInput channel index (0-based).
sampleThe sample value to write.

◆ SetPreset() [1/3]

void Csound.Unity.CsoundUnity.SetPreset ( CsoundUnityPreset preset)
inline

Set a CsoundUnityPreset to this CsoundUnity instance.

If the preset csoundFileName is different from this CsoundUnity instance csoundFileName the preset will not be set and an error will be logged.

Parameters
presetThe preset to apply to this instance.

◆ SetPreset() [2/3]

CsoundUnityPreset Csound.Unity.CsoundUnity.SetPreset ( string presetData)
inline

Set a CsoundUnityPreset to this CsoundUnity instance using presetData.

The set preset will be returned. The name of the preset will be the one found inside presetData, if not empty. Otherwise a default presetName will be used.

Preset data should represent a CsoundUnityPreset in JSON format.

If the preset csoundFileName is different from this CsoundUnity instance csoundFileName the preset will not be set and an error will be logged.

Parameters
presetDataJSON string representing a CsoundUnityPreset.
Returns
The applied CsoundUnityPreset, or null if loading or applying it failed.

◆ SetPreset() [3/3]

CsoundUnityPreset Csound.Unity.CsoundUnity.SetPreset ( string presetName,
string presetData )
inline

Set a CsoundUnityPreset to this CsoundUnity instance using a presetName and presetData. The set preset will be returned.

Preset data should represent a CsoundUnityPreset in JSON format.

If the preset csoundFileName is different from this CsoundUnity instance csoundFileName the preset will not be set and an error will be logged.

Parameters
presetNameName to assign to the preset (overrides the name in the JSON).
presetDataJSON string representing a CsoundUnityPreset.
Returns
The applied CsoundUnityPreset, or null if loading or applying it failed.

◆ SetPvsChannel() [1/2]

CsoundPvsChannelStatus Csound.Unity.CsoundUnity.SetPvsChannel ( string name,
float[] source )
inline

Write exactly N+2 floats and increment the frame counter on success. Use once per new spectral frame.

Parameters
nameThe channel name.
sourceExactly N+2 floats in the destination's pair format.
Returns
The write result; no resize or channel creation occurs. UnsupportedPlatform in WebGL.

◆ SetPvsChannel() [2/2]

CsoundPvsChannelStatus Csound.Unity.CsoundUnity.SetPvsChannel ( string name,
float[] source,
CsoundPvsChannelInfo frame )
inline

Write a snapshot with matching FFT/hop/window/format, preserving its frame counter.

Parameters
nameThe channel name.
sourceExactly frame.FrameLength floats.
frameSnapshot metadata from a compatible source channel, including its frame counter.
Returns
The write result; mismatched layouts return ShapeMismatch. UnsupportedPlatform in WebGL.

◆ SetScoreOffsetSeconds()

void Csound.Unity.CsoundUnity.SetScoreOffsetSeconds ( MYFLT value)
inline

Csound score events prior to the specified time are not performed, and 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.

Parameters
valueTime offset in seconds from the start of the score.

◆ SetStringArrayChannel()

CsoundArrayChannelStatus Csound.Unity.CsoundUnity.SetStringArrayChannel ( string name,
string[] source )
inline

Replace all S[] elements from UTF-8 text without resizing the channel. Null elements become empty strings; embedded null characters are rejected. Native buffers may grow. Not audio-thread safe.

Parameters
nameThe channel name.
sourceExactly one value per current element.
Returns
The write result; UnsupportedPlatform in WebGL, Busy in an audio callback.

◆ SetStringChannel()

void Csound.Unity.CsoundUnity.SetStringChannel ( string channel,
string val )
inline

Sets a string channel in Csound. Used in connection with a chnget opcode in your Csound instrument.

Parameters
channelName of the Csound string channel.
valString value to assign.

◆ SetTable()

void Csound.Unity.CsoundUnity.SetTable ( int table,
int index,
MYFLT value )
inline

Sets the value of a slot in a function table. The table number and index are assumed to be valid.

Parameters
tableThe function table number.
indexZero-based slot index to write.
valueThe value to write into the slot.

◆ Stop()

void Csound.Unity.CsoundUnity.Stop ( )
inline

Stops and disposes the current Csound instance. After this, Initialize or Restart can be called to start again.

◆ StopMorph()

void Csound.Unity.CsoundUnity.StopMorph ( )
inline

Stops an in-progress morph started by MorphToPreset. Channel values remain at whatever point the morph reached when stopped.

◆ TryApplyPreset()

bool Csound.Unity.CsoundUnity.TryApplyPreset ( CsoundUnityPreset preset)
inlinepackage

◆ WouldCreateCircle()

bool Csound.Unity.CsoundUnity.WouldCreateCircle ( CsoundUnity newSource)
inline

Returns true if routing audio from newSource into this instance would create a circular dependency in the audio graph.

The algorithm performs a BFS starting from this node and follows outgoing edges — i.e. it finds every instance X that lists any already-reachable node as one of its audioInputRoutes sources, then checks whether X equals newSource .

Because audioInputRoutes only stores incoming edges, the search must inspect all live CsoundUnity instances in the scene.

Returns
True when the route would close a loop, so it must not be added.
Parameters
newSourceThe instance that would become a source for this one.

◆ WritePreset()

void Csound.Unity.CsoundUnity.WritePreset ( CsoundUnityPreset preset,
string path )
inlinestatic

Write a CsoundUnityPreset at the specified path inside the Assets folder. You can pass a full path, the Assets folder path will be extracted. Subfolders in the preset name are created as needed; the stored name is the file's leaf name. Overwriting an existing asset preserves its GUID and references.

Parameters
presetThe preset ScriptableObject to write.
pathTarget directory path; the Assets sub-path will be extracted automatically.

Member Data Documentation

◆ audioInputRoutes

List<AudioInputRoute> Csound.Unity.CsoundUnity.audioInputRoutes = new List<AudioInputRoute>()

Audio-rate input routes: each entry reads a named audio channel from another CsoundUnity instance and injects it into this instance's spin buffer before every PerformKsmps call.

◆ audioRate

int Csound.Unity.CsoundUnity.audioRate = 44100

The audio sample rate (sr) passed to Csound on initialization. Defaults to AudioSettings.outputSampleRate unless overrideSamplingRate is true.

◆ controlRate

int Csound.Unity.CsoundUnity.controlRate = 44100

The Csound control rate (kr) computed as audioRate / ksmps. Updated automatically whenever audioRate or ksmps changes.

◆ csoundScore

string Csound.Unity.CsoundUnity.csoundScore

the score to send via editor

◆ environmentSettings

List<EnvironmentSettings> Csound.Unity.CsoundUnity.environmentSettings = new List<EnvironmentSettings>()

The list of the Environment Settings that will be set on start, using csoundSetGlobalEnv. Each setting can be used to specify the path of an environment variable. These settings will be applied to this CsoundUnity instance when the CsoundUnityBridge is created.

◆ fadeInSeconds

float Csound.Unity.CsoundUnity.fadeInSeconds = 0f

Ramps the output up from silence over this many seconds when Csound starts, masking the transient of chained sources that have not filled their buffers yet. 0 disables it, which is the default: playback starts at full level.

In seconds rather than samples so it means the same thing at any output sample rate, and honoured by all three audio paths. Applies from the next Init().

◆ GLOBAL_TAG

const string Csound.Unity.CsoundUnity.GLOBAL_TAG = "(GLOBAL)"
staticpackage

◆ initializeOnAwake

bool Csound.Unity.CsoundUnity.initializeOnAwake = true

If true CsoundUnity will initialize automatically in Awake. Set to false to initialize manually by calling Initialize.

◆ ksmps

int Csound.Unity.CsoundUnity.ksmps = 32

Intended ksmps value. Stored so that when the audio device changes (sr changes) the control rate is recomputed as kr = sr / ksmps rather than being rounded from the old kr, which would yield a different ksmps.

◆ logCsoundOutput

bool Csound.Unity.CsoundUnity.logCsoundOutput = false

If true, all Csound output messages will be sent to the Unity output console. Note that this can slow down performance if there is a lot of information being printed.

◆ loudVolumeWarning

bool Csound.Unity.CsoundUnity.loudVolumeWarning = true

If true it will print warnings in the console when the output volume is too high, and clamp every sample louder than loudWarningThreshold to it.

◆ loudWarningThreshold

float Csound.Unity.CsoundUnity.loudWarningThreshold = 10f

The ceiling: a sample louder than this is clamped to it, and the console names the level it reached. 1 is full scale, so the default of 10 only catches real runaways.

◆ mute

bool Csound.Unity.CsoundUnity.mute = false

Silences this instance's audio output. Csound keeps performing: the score advances, so unmuting drops back in on the beat rather than resuming where it left off, and input (audio input routes, native audio input, clip audio) keeps flowing in.

Instances routed from this one receive silence while it is muted — they do not keep hearing the last block it produced. To stop the DSP work as well, and pick up exactly where it stopped, use pauseProcessing instead.

Not to be confused with AudioSource.mute, which silences this instance's own monitoring but leaves it feeding its routed destinations at full level (and has no effect at all on the RootOutput audio path, which bypasses the AudioSource).

◆ muteAudioInputRoutes

bool Csound.Unity.CsoundUnity.muteAudioInputRoutes = false

When true, all Audio Input Routes are silenced without removing them.

◆ namedAudioChannelDataDict

readonly Dictionary<string, MYFLT[]> Csound.Unity.CsoundUnity.namedAudioChannelDataDict = new Dictionary<string, MYFLT[]>()

Named audio channels produced by this instance, shown in the CsoundUnityChild inspector.

These are the live working arrays, filled sample by sample by the audio thread while a block is being produced. Reading them from another thread — the main thread, or another instance's audio callback — can therefore observe a half-written block, and carries no memory barrier, so on 32-bit ARM a MYFLT can be read torn. Both are audible as intermittent clicks.

Audio input routing does not read this: it reads the completed snapshots published at the end of each block. Anything else that needs this data across threads should do the same, through GetAudioChannelReader, rather than reading here directly.

◆ nativeAudioInputProvider

volatile INativeAudioInputProvider Csound.Unity.CsoundUnity.nativeAudioInputProvider

Optional native audio input provider (e.g. CsoundUnityNativeAudioInput). When set, INativeAudioInputProvider.FillSpinBuffer is called once per ksmps boundary on the audio thread, before PerformKsmps. Assign on the main thread; reads on the audio thread are safe due to the volatile qualifier.

◆ overrideSamplingRate

bool Csound.Unity.CsoundUnity.overrideSamplingRate = false

If true you can override the default Csound control rate with a custom value. The default value is AudioSettings.outputSampleRate. Ksmps will be calculated by Csound so there's no need to set it in your csd.

◆ packageName

const string Csound.Unity.CsoundUnity.packageName = "com.csound.csoundunity"
static

The name of this package.

◆ packageVersion

const string Csound.Unity.CsoundUnity.packageVersion = "4.0.0-alpha.3"
static

The version of this package.

◆ pauseProcessing

bool Csound.Unity.CsoundUnity.pauseProcessing = false

Suspends this instance: the output is silenced and Csound stops performing, so no DSP work is done at all. The score is frozen, so clearing the flag resumes from exactly where it stopped.

Unlike disabling the GameObject or calling Stop, nothing is torn down: the Csound instance, its state and its channel values are all preserved, and resuming is immediate. Instances routed from this one receive silence while it is paused.

Use mute instead when the instance should stay in time.

◆ processClipAudio

bool Csound.Unity.CsoundUnity.processClipAudio

If true Csound uses as an input the AudioClip attached to this AudioSource. If false, no processing occurs on the attached AudioClip.

Clip audio keeps reaching Csound while the instance is muted — muting silences the output, not the input, so effects fed by the clip stay warm. It stops under pauseProcessing, where nothing would consume it.

◆ updateOutputBuffer

bool Csound.Unity.CsoundUnity.updateOutputBuffer = false

When true, the full Csound output buffer (all nchnls channels) is copied into OutputBuffer each DSP block, making it available to visualisers and external audio routing. Off by default to avoid the per-block copy overhead.

◆ webGLAssetsList

List<string> Csound.Unity.CsoundUnity.webGLAssetsList

List of asset paths that will be loaded asynchronously by the WebGL Csound bridge before performance begins (e.g. sample files that must be available in the virtual file system).

Property Documentation

◆ ApplicationIsQuitting

bool Csound.Unity.CsoundUnity.ApplicationIsQuitting
staticgetpackage

The static half of IsShuttingDown, for the other components in the package: they make the same main-thread AudioSource calls and need them kept away from FMOD teardown, and this is the part that holds whether or not OnApplicationQuit reached them.

◆ availableAudioChannels

List<string> Csound.Unity.CsoundUnity.availableAudioChannels
get

list to hold available audioChannels names

◆ channels

List<CsoundChannelController> Csound.Unity.CsoundUnity.channels
get

list to hold channel data

◆ csoundFileGUID

string Csound.Unity.CsoundUnity.csoundFileGUID
get

the unique guid of the csd file

◆ csoundFileName

string Csound.Unity.CsoundUnity.csoundFileName
get

The file CsoundUnity will try to load. You can only load one file with each instance of CsoundUnity, but you can use as many instruments within that file as you wish.You may also create as many of CsoundUnity objects as you wish.

◆ csoundString

string Csound.Unity.CsoundUnity.csoundString
get

a string to hold all the csoundFile content

◆ CurrentPreset

CsoundUnityPreset Csound.Unity.CsoundUnity.CurrentPreset
get

The preset currently applied to this instance, or null if none is.

Set it in the inspector to have it applied when Csound starts. A preset built at runtime from JSON lives here too, but only until the next reload: Unity serialises a reference to an asset, and one of those has no asset behind it.

◆ CurrentPresetName

string Csound.Unity.CsoundUnity.CurrentPresetName
get

The name of the current preset, or empty if none is set.

Kept apart from CurrentPreset because the two can disagree: a global preset is a snapshot of the whole component rather than a CsoundUnityPreset, so it can only leave a name behind.

◆ DspLoad

float Csound.Unity.CsoundUnity.DspLoad = 0f
get

Exponentially smoothed DSP load: fraction of the DSP time budget used by this instance. 0 = idle, 1 = full budget consumed, >1 = overload. Only meaningful when MeasureDspLoad is true.

◆ DspMeasuredBlocks

long Csound.Unity.CsoundUnity.DspMeasuredBlocks
get

Number of DSP blocks measured since the last reset. Stays zero until measurement is enabled with MeasureDspLoad; retains its value while measurement is off.

◆ DspOverBudgetBlocks

long Csound.Unity.CsoundUnity.DspOverBudgetBlocks
get

Measured blocks whose Csound work exceeded the block's audio time budget. This is a timing counter, not a count reported by the audio device. Stays zero until measurement is enabled with MeasureDspLoad; retains its value while measurement is off.

◆ DspPeakBlockMilliseconds

double Csound.Unity.CsoundUnity.DspPeakBlockMilliseconds
get

Highest measured DSP block duration in milliseconds since the last reset. Covers the same Csound work as DspLoad; excludes other Unity audio sources. Stays zero until measurement is enabled with MeasureDspLoad; retains its value while measurement is off.

◆ HasCompiled

bool Csound.Unity.CsoundUnity.HasCompiled
get

true when a CSD was assigned and compiled successfully.

Unlike IsInitialized, which is true even when no CSD is assigned, HasCompiled is false when CsoundUnity was started without a CSD, when compilation failed, and after a CsoundReset until the next successful compilation.

◆ isFinite

bool Csound.Unity.CsoundUnity.isFinite
get

Csound runs indefinitely — not finite.

◆ IsInitialized

bool Csound.Unity.CsoundUnity.IsInitialized
get

Is Csound initialized?

◆ isRealtime

bool Csound.Unity.CsoundUnity.isRealtime
get

Csound must run at the system audio rate.

◆ IsWaitingForUserGesture

bool Csound.Unity.CsoundUnity.IsWaitingForUserGesture
get

True while a browser is withholding audio until the page gets a real click, tap or key press. Always false off WebGL, so a scene can read it without a platform check.

This is the difference IsInitialized cannot express: not initialized yet lasts a few frames on every platform, while this lasts until the page is clicked, and it is the only one of the two a "click to start" notice should follow. The gesture itself needs no handling — the browser delivers it, Csound starts, and OnCsoundInitialized fires as usual.

void Update() =&gt; _notice.SetActive(_csound.IsWaitingForUserGesture);

◆ LastLoudPeak

float Csound.Unity.CsoundUnity.LastLoudPeak
getpackage

The last peak an audio path had to clamp, and when it happened. The inspector shows them while it is going on: the console can be cleared, filtered, or simply not watched, and the clamp itself sounds like a loud mix rather than like a fault.

◆ LastLoudTime

float Csound.Unity.CsoundUnity.LastLoudTime = float.NegativeInfinity
getpackage

◆ length

DiscreteTime? Csound.Unity.CsoundUnity.length
get

Infinite generator — length is unknown.

◆ LoudLimit

float Csound.Unity.CsoundUnity.LoudLimit
getpackage

The sample value the audio paths silence a sample at. PositiveInfinity when the check is off, so a sample that is not a number is caught either way: on RootOutput one of those does not stay inside this instance, it goes into Unity's main output.

◆ MeasureDspLoad

bool Csound.Unity.CsoundUnity.MeasureDspLoad
getset

Turns the DSP load measurement on and off. It costs a little time on the audio thread, so it is off unless something is reading it.

◆ OutputBuffer

float [] Csound.Unity.CsoundUnity.OutputBuffer
get

The most recently completed DSP output buffer. Contains interleaved samples for all Csound output channels when updateOutputBuffer is true; otherwise the array holds the single-channel Unity output.

Reading this property pulls the latest block published by the audio thread, so the returned array is always a complete block and never one being rewritten underneath the caller. When no new block has been produced since the last read the previous contents are returned unchanged, so polling faster than the DSP rate is free. Read it from the main thread.

◆ OutputChannels

int Csound.Unity.CsoundUnity.OutputChannels
get

Number of audio channels interleaved in OutputBuffer (equals Csound's nchnls when updateOutputBuffer is true), or 1 before the first block has been published.

Read straight from the published block rather than cached when the buffer is fetched, so that reading this before OutputBuffer cannot hand back a stale count.

◆ PerformanceFinished

bool Csound.Unity.CsoundUnity.PerformanceFinished
get

True when Csound's score has ended naturally (all score events have been performed). This is set on the audio thread; for main-thread notification subscribe to OnCsoundPerformanceFinished.

◆ samplingRateSettingsInfo

string Csound.Unity.CsoundUnity.samplingRateSettingsInfo
get

Returns a human-readable summary of the current sampling-rate settings in the form "sr: X, kr: Y, ksmps: Z". Used by the inspector.

◆ StartupFadeFrames

int Csound.Unity.CsoundUnity.StartupFadeFrames
getpackage

Length of the startup fade in output frames, or 0 when fadeInSeconds leaves it off. Plain arithmetic over a sample rate cached on the main thread, so the audio paths can ask for it without calling into Unity.

◆ unsupportedWidgets

List<string> Csound.Unity.CsoundUnity.unsupportedWidgets
get

Cabbage widgets present in the current csd that the parser does not build a channel for. Empty when everything in the csd is supported.

◆ WebGLSpatialization

bool Csound.Unity.CsoundUnity.WebGLSpatialization
getset

Whether the position is sent to the csd on WebGL.

Event Documentation

◆ OnChannelsUpdated

ChannelsUpdated Csound.Unity.CsoundUnity.OnChannelsUpdated

Raised after a batch of channels has been written from outside the UI — applying a preset, most of the time.

The UI components drive their channels but do not watch them, so without this a preset applied while the scene runs changed the sound and left every control where it was. They subscribe here and re-read, the same way they already do for OnCsoundInitialized.

◆ OnCsoundInitialized

CsoundInitialized Csound.Unity.CsoundUnity.OnCsoundInitialized

An event that will be executed when Csound is initialized.

◆ OnCsoundPerformanceFinished

CsoundPerformanceFinishedDelegate Csound.Unity.CsoundUnity.OnCsoundPerformanceFinished

An event fired on the main thread when Csound performance ends naturally (score complete). CsoundUnity will call Stop immediately after firing this event.

◆ OnCsoundPerformKsmps

CsoundPerformKsmps Csound.Unity.CsoundUnity.OnCsoundPerformKsmps

An event fired on the audio thread after every PerformKsmps call. Keep the handler extremely lightweight to avoid audio dropouts.

Fires while the instance is muted, since muting silences the output but Csound keeps performing; it does not fire while pauseProcessing is set, because then there is no PerformKsmps to report.

◆ OnCsoundStopped

CsoundStopped Csound.Unity.CsoundUnity.OnCsoundStopped

An event that will be executed when Csound is stopped via Stop.


The documentation for this class was generated from the following files: