node package manager

csound-api

Csound API

Build status Build status npm npm Known Vulnerabilities

This package is a Node.js Addon for using Csound through its C API. The functions in this package try to match the functions in Csound’s API as closely as possible, and this package adds PerformAsync and PerformKsmpsAsync functions that run Csound in a background thread. If you require this package using

const csound = require('csound-api');

then you can use Csound’s API as, for example,

function messageCallback(attributes, string) {
  console.log(string);
}
const Csound = csound.Create();
csound.SetMessageCallback(Csound, messageCallback);
csound.Message(Csound, 'hello, world');

The equivalent in C would be something like

void messageCallback(CSOUND *Csound, int attributes, const char *format, va_list argumentList) {
  vprintf(format, argumentList);
}
CSOUND *Csound = csoundCreate(NULL);
csoundSetMessageCallback(Csound, messageCallback);
csoundMessage(Csound, "hello, world");

Contents

Installing

Before you install this package, you need Boost 1.53.0 or later and Csound.

On macOS

The easiest way to install Boost is probably through Homebrew. To install Homebrew, follow the instructions at brew.sh. Then, run brew install boost in a Terminal.

If you aren’t able to build Csound from its source code, the most reliable way to install Csound so that you can build csound-api is to run an installer in a disk image you can download from https://github.com/csound/csound/releases/latest (scroll until you find the Downloads section). When you double-click the installer in the disk image, macOS may not allow the installer to run because it’s from an unidentified developer. To run the installer after this happens, open System Preferences, choose Security & Privacy, and click Open Anyway in the bottom half of the window.

After you install Csound using the disk image, you must create a symbolic link to Csound’s headers in /usr/local/include. To do this, open a Terminal and run

ln -s /Library/Frameworks/CsoundLib64.framework/Headers /usr/local/include/csound

After you install Boost and Csound, you can install this package by running

npm install csound-api

On Linux

To install Boost, run

sudo apt-get install -y libboost-dev

To install Csound so that you can build csound-api, run

sudo apt-get install -y libcsound64-dev

After you install Boost and Csound, you can install this package by running

npm install csound-api

On Windows

In addition to Boost and Csound, you need Python 2.7 and Visual Studio.

To install Python 2.7, visit https://www.python.org/downloads/windows/ and download and run an installer for the latest release of Python 2.7. Make sure you add python.exe to your Windows Path when you install Python.

To install Visual Studio, visit https://www.visualstudio.com and download and run an installer for Visual Studio. (Visual Studio Community is free.) Make sure you install the Windows 8.1 software development kit (SDK) when you install Visual Studio. One way to do this is to perform a custom installation and, when selecting features, select Windows and Web Development > Windows 8.1 and Windows Phone 8.0/8.1 Tools > Tools and Windows SDKs.

To install Boost, you can download and run an installer of a prebuilt binary from https://sourceforge.net/projects/boost/files/boost-binaries/.

To install Csound, you can download and run an installer from https://github.com/csound/csound/releases/latest (scroll until you find the Downloads section).

If you use Csound 6.07 or earlier, you must also create a csound64.lib file after you install Csound. To do this, open an administrator Command Prompt in C:\Program Files\Csound6_x64\bin and run

if not defined ProgramFiles(x86) set ProgramFiles(x86)=%ProgramFiles%
set PATH=%PATH%;%ProgramFiles(x86)%\Microsoft Visual Studio 14.0\VC\bin
echo LIBRARY csound64.dll > csound64.def && echo EXPORTS >> csound64.def
for /f "skip=19 tokens=4" %G in ('dumpbin /exports csound64.dll') do @echo %G >> csound64.def
if not exist ..\lib\NUL mkdir ..\lib
lib /def:csound64.def /out:..\lib\csound64.lib /machine:x64

After you install Python 2.7, Visual Studio, Boost, and Csound, you can install this package by running

set CL=/I"C:\path\to\boost"
npm install csound-api

where C:\path\to\boost is the path to Boost.

Examples

Play a 440 Hz sine tone.

const csound = require('csound-api');
const Csound = csound.Create();
csound.SetOption(Csound, '--output=dac');
csound.CompileOrc(Csound, `
  0dbfs = 1
  giFunctionTableID ftgen 0, 0, 16384, 10, 1
  instr A440
    outc oscili(0.5 * 0dbfs, 440, giFunctionTableID)
  endin
`);
csound.ReadScore(Csound, `
  i "A440" 0 1
  e
`);
if (csound.Start(Csound) === csound.SUCCESS)
  csound.Perform(Csound);
csound.Destroy(Csound);

Run Csound asynchronously, and stop Csound in mid-performance.

const csound = require('csound-api');
const Csound = csound.Create();
csound.SetOption(Csound, '--output=dac');
csound.CompileOrc(Csound, `
  0dbfs = 1
  instr SawtoothSweep
    // This outputs a sawtooth wave with a fundamental frequency that starts at
    // 110 Hz, rises to 220 Hz over 1 second, and then falls back to 110 Hz over
    // 1 second. The score plays this instrument for 2 seconds, but the call to
    // setTimeout() stops Csound after 1 second, so only the rise is heard.
    outc vco2(0.5 * 0dbfs, expseg(110, 1, 220, 1, 110))
  endin
`);
csound.ReadScore(Csound, `
  i "SawtoothSweep" 0 2
  e
`);
if (csound.Start(Csound) === csound.SUCCESS) {
  csound.PerformAsync(Csound, () => csound.Destroy(Csound));
  setTimeout(() => csound.Stop(Csound), 1000);
}

Log a list of Csound’s opcodes.

const csound = require('csound-api');
const Csound = csound.Create();
const opcodes = [];
csound.NewOpcodeList(Csound, opcodes);
console.log(opcodes);
csound.DisposeOpcodeList(Csound, opcodes);
csound.Destroy(Csound);

Log an abstract syntax tree parsed from an orchestra.

const csound = require('csound-api');
const Csound = csound.Create();
const ASTRoot = csound.ParseOrc(Csound, `
  0dbfs = 1
  giFunctionTableID ftgen 0, 0, 16384, 10, 1
  instr A440
    outc oscili(0.5 * 0dbfs, 440, giFunctionTableID)
  endin
`);
console.log(ASTRoot);
csound.DeleteTree(Csound, ASTRoot);
csound.Destroy(Csound);

Contributing

Open an issue, or fork this project and make a pull request.

API Coverage

Here are the properties and functions you can use assuming you require this package as

const csound = require('csound-api');

Instantiation

Csound = csound.Create([value]) creates a new Csound object and optionally associates a value with it; value can be an object, a function, a string, a number, a Boolean, null, or undefined. You can retrieve a value associated with a Csound object using csound.GetHostData and associate a new value using csound.SetHostData. You must pass the returned Csound object as the first argument to most other functions in this package, and you should pass Csound to csound.Destroy when you’re finished using Csound.

csound.Destroy(Csound) frees resources used by a Csound object.

versionTimes1000 = csound.GetVersion() gets Csound’s version number multiplied by 1,000. For example, if you’re using Csound 6.08, then versionTimes1000 will be 6,080.

versionTimes100 = csound.GetAPIVersion() gets the version of Csound’s API, multiplied by 100. For example, if you’re using version 4.0 of Csound’s API, then versionTimes100 will be 400.

result = csound.Initialize([options]) is called by csound.Create, but you can call it before any calls to csound.Create to prevent initialization of exit and signal handling functions. Pass csound.INIT_NO_ATEXIT to prevent initialization of exit functions, csound.INIT_NO_SIGNAL_HANDLER to prevent initialization of signal handling functions, and a bitmask of both to prevent both. This can be useful when debugging segmentation faults using a package like segfault-handler. The returned result indicates the state of initialization:

When result is Initialization
greater than 0 was already performed successfully
equal to 0 is successful
less than 0 failed because of an error

Performance

AST = csound.ParseOrc(Csound, orchestraString) parses a string containing a Csound orchestra into an abstract syntax tree (AST). The returned AST is an object representing the root node of the AST. AST nodes have a number of read-only properties:

type
is a number indicating the type of token. One way to determine how types correspond to tokens is to build Csound from its source code and examine the Bison-generated file csound_orcparse.h.
value
is an object describing the token. It has several read-only properties:
type
is a number indicating the type of token. This need not be the same as the type of the AST object.
lexeme
is a string. This is usually the string value of the token, but not always. For example, operator opcodes like + have lexemes like ##add.
value
is a number equal to the value of the token if it is an integer, and 0 otherwise.
fvalue
is a number equal to the value of the token if it is not an integer, and 0 otherwise.
line
is the line number where the token occurs.
left
is an AST node that generally represents the first output argument of an opcode.
right
is an AST node that generally represents the first input argument of an opcode.
next
is an AST node that is the first node of a linked list of all other arguments of an opcode. Output arguments precede input arguments. For example, in an AST node parsed from
kFrequency, kAmplitude pvread kTime, "file.pvx", 1
the pvread node will have a left node for the kFrequency output argument; a right node for the kTime input argument; and next nodes for the kAmplitude output argument, "file.pvx" input argument, and 1 input argument.

You can compile the AST using csound.CompileTree, and you should pass the AST to csound.DeleteTree when you’re finished with it.

status = csound.CompileTree(Csound, AST) compiles an AST returned from csound.ParseOrc, adding instruments and other structures to Csound. The returned status is a Csound status code.

csound.DeleteTree(Csound, AST) frees resources used by an AST.

status = csound.CompileOrc(Csound, orchestraString) compiles a string containing a Csound orchestra, adding instruments and other structures to Csound. The returned status is a Csound status code.

number = csound.EvalCode(Csound, orchestraString) gets a number passed to a global return opcode in orchestraString. For example,

const csound = require('csound-api');
const Csound = csound.Create();
csound.SetOption(Csound, '--nosound');
if (csound.Start(Csound) === csound.SUCCESS) {
  console.log(csound.EvalCode(Csound, `
    iResult = 19 + 23
    return iResult
  `));
}

logs the number 42. Before using this function, you must start Csound — that is, you must pass Csound to csound.Start, which must return the csound.SUCCESS status code.

status = csound.CompileArgs(Csound, commandLineArguments) compiles instruments, sets options, and performs other actions according to command line arguments in the commandLineArguments string array, without starting Csound. For example,

const csound = require('csound-api');
const Csound = csound.Create();
csound.CompileArgs(Csound, ['csound', 'my.orc', 'my.sco']);

compiles the orchestra in my.orc and the score in my.sco, but does not start Csound. To start Csound after calling csound.CompileArgs, pass Csound to csound.Start. To compile Csound files using command line arguments and also start Csound, use csound.Compile. The returned status is a Csound status code.

status = csound.Start(Csound) prepares Csound for performance — that is, to be passed to csound.PerformAsync, csound.Perform, or csound.PerformKsmps. The returned status is a Csound status code.

status = csound.Compile(Csound, commandLineArguments) compiles instruments, sets options, and performs other actions according to command line arguments in the commandLineArguments string array, and also starts Csound. To compile Csound files using command line arguments without starting Csound, use csound.CompileArgs. The returned status is a Csound status code.

status = csound.CompileCsd(Csound, filePath) compiles the CSD file located at filePath and starts Csound. The returned status is a Csound status code.

csound.PerformAsync(Csound, function(result)) performs score and input events on a background thread, and calls the passed function when the performance stops. The result passed to this function is a number that indicates the reason performance stopped:

When result is Performance stopped because
greater than 0 the end of the score was reached
equal to 0 csound.Stop was called
less than 0 an error occurred

result = csound.Perform(Csound) performs score and input events on the main thread. The returned result is the same as the result passed to the function argument of csound.PerformAsync.

csound.PerformKsmpsAsync(Csound, controlPeriodFunction, performanceFinishedFunction) performs score and input events on a background thread, calling controlPeriodFunction after a control period, and performanceFinishedFunction when the performance is finished.

performanceFinished = csound.PerformKsmps(Csound) performs one control period of samples on the main thread, returning true if the performance is finished and false otherwise.

csound.Stop(Csound) stops a Csound performance asynchronously.

status = csound.Cleanup(Csound) frees resources after the end of a Csound performance. The returned status is a Csound status code.

csound.Reset(Csound) frees resources after the end of a Csound performance (just like csound.Cleanup) and prepares for a new performance.


Attributes

sampleRate = csound.GetSr(Csound) gets sr, the Csound sample rate (also called the audio rate or a‑rate).

controlRate = csound.GetKr(Csound) gets kr, the Csound control rate (also called the k‑rate).

samplesPerControlPeriod = csound.GetKsmps(Csound) gets ksmps, the number of digital audio samples in one control period.

outputChannelCount = csound.GetNchnls(Csound) gets nchnls, the number of audio output channels.

inputChannelCount = csound.GetNchnlsInput(Csound) gets nchnls_i, the number of audio input channels.

fullScalePeakAmplitude = csound.Get0dBFS(Csound) gets 0dBFS, the maximum value of a sample of audio.

performedSampleCount = csound.GetCurrentTimeSamples(Csound) gets the number of samples performed by Csound. You can call this function during a performance. For the elapsed time in seconds of a performance, divide performedSampleCount by the sample rate, or use csound.GetScoreTime.

bytesPerFloat = csound.GetSizeOfMYFLT() gets the number of bytes that Csound uses to represent floating-point numbers. When Csound is compiled to use double-precision samples, bytesPerFloat is 8. Otherwise, it’s 4.

value = csound.GetHostData(Csound) gets a value associated with a Csound object using csound.Create or csound.SetHostData.

csound.SetHostData(Csound, value) associates a value with a Csound object; value can be an object, a function, a string, a number, a Boolean, null, or undefined. You can retrieve a value associated with a Csound object using csound.GetHostData.

status = csound.SetOption(Csound, commandLineArgumentString) sets a Csound option as if commandLineArgumentString was input as a command line argument. For example,

const csound = require('csound-api');
const Csound = csound.Create();
csound.SetOption(Csound, '--output=dac');

sets up Csound to output audio through your computer’s speakers. The returned status is a Csound status code.

queuesDebugMessages = csound.GetDebug(Csound) gets a Boolean indicating whether Csound adds debug messages to its message queue. Use csound.SetDebug to set this value.

csound.SetDebug(Csound, queuesDebugMessages) sets a Boolean indicating whether Csound adds debug messages to its message queue. Use csound.GetDebug to get this value.


General Input/Output

audioOutputName = csound.GetOutputName(Csound) gets the name of the audio output — the value of the --output command line flag. For example,

const csound = require('csound-api');
const Csound = csound.Create();
csound.SetOption(Csound, '--output=dac');
console.log(csound.GetOutputName(Csound));

logs dac.

csound.SetOutput(Csound, name[, type[, format]]) sets the name, file type, and encoding format of Csound output. If name is 'dac', then Csound will output audio through your computer’s speakers. Otherwise, name is the name of the file to which Csound will write your performance. The optional type is a string indicating one of libsndfile’s supported file types:

String File type
'wav' Microsoft WAV
'aiff' Apple AIFF/AIFC
'au' Sun Au
'raw' Audio in any format
'paf' Ensoniq PARIS Audio Format
'svx' Amiga 8SVX
'nist' NIST Speech File Manipulation Software (SPHERE)
'voc' Creative Labs Voice
'ircam' Berkeley/IRCAM/CARL Sound Format
'w64' Sound Forge Wave 64
'mat4' MATLAB MAT-File Level 4
'mat5' MATLAB MAT-File Level 5
'pvf' Nullsoft Portable Voice Format
'htk' Hidden Markov Model Toolkit
'sds' MIDI Sample Dump Standard
'avr' Audio Visual Research
'wavex' Microsoft WAV Extensible
'sd2' Sound Designer II
'flac' Free Lossless Audio Codec
'caf' Apple Core Audio Format
'wve' Psion waveform
'ogg' Ogg container
'mpc2k' Akai MPC2000
'rf64' European Broadcasting Union RF64

The optional format is a string indicating one of libsndfile’s encoding formats:

String Encoding format
'schar' Signed 8‑bit integer
'short' Signed 16‑bit integer
'24bit' Signed 24‑bit integer
'long' Signed 32‑bit integer
'uchar' Unsigned 8‑bit integer
'float' 32‑bit floating-point number
'double' 64‑bit floating-point number
'ulaw' µ‑law
'alaw' A‑law
'vorbis' Vorbis

To learn about the encoding formats you can use with each file type, see the table at http://www.mega-nerd.com/libsndfile/.


Score Handling

status = csound.ReadScore(Csound, scoreString) compiles a string containing a Csound score, adding events and other structures to Csound. The returned status is a Csound status code.

elapsedTime = csound.GetScoreTime(Csound) gets the elapsed time in seconds of a Csound performance. You can call this function during a performance. For the number of samples performed by Csound, multiply elapsedTime by the sample rate, or use csound.GetCurrentTimeSamples.

performsScoreEvents = csound.IsScorePending(Csound) gets a Boolean indicating whether Csound performs events from a score in addition to realtime events. Use csound.SetScorePending to set this value.

csound.SetScorePending(Csound, performsScoreEvents) sets a Boolean indicating whether Csound performs events from a score in addition to realtime events. Use csound.IsScorePending to get this value.

scoreEventStartTime = csound.GetScoreOffsetSeconds(Csound) gets the amount of time subtracted from the start time of score events. Use csound.SetScoreOffsetSeconds to set this time.

csound.SetScoreOffsetSeconds(Csound, scoreEventStartTime) sets an amount of time to subtract from the start times of score events. For example,

const csound = require('csound-api');
const Csound = csound.Create();
csound.SetOption(Csound, '--nosound');
csound.CompileOrc(Csound, `
  instr 1
    prints "hello, world\n"
  endin
`);
const delay = 5;
csound.ReadScore(Csound, `
  i 1 ${delay} 0
  e
`);
csound.SetScoreOffsetSeconds(Csound, delay);
if (csound.Start(Csound) === csound.SUCCESS)
  csound.Perform(Csound);
csound.Destroy(Csound);

prints hello, world immediately, not after a 5 second delay. Use csound.GetScoreOffsetSeconds to get this time.

csound.RewindScore(Csound) restarts a compiled score at the time returned by csound.GetScoreOffsetSeconds.


Messages & Text

csound.Message(Csound, string) adds to the Csound message queue a message consisting of a string.

csound.MessageS(Csound, attributes, string) adds to the Csound message queue a message with attributes applied to a string. The value of attributes is a bit mask of

  • a type specified by one of csound.MSG_DEFAULT, csound.MSG_ERROR, csound.MSG_ORCH, csound.MSG_REALTIME, or csound.MSG_WARNING;

  • a text color specified by one of csound.MSG_FG_BLACK, csound.MSG_FG_RED, csound.MSG_FG_GREEN, csound.MSG_FG_YELLOW, csound.MSG_FG_BLUE, csound.MSG_FG_MAGENTA, csound.MSG_FG_CYAN, or csound.MSG_FG_WHITE;

  • the bold specifier csound.MSG_FG_BOLD;

  • the underline specifier csound.MSG_FG_UNDERLINE; and

  • a background color specified by one of csound.MSG_BG_BLACK, csound.MSG_BG_RED, csound.MSG_BG_GREEN, csound.MSG_BG_ORANGE, csound.MSG_BG_BLUE, csound.MSG_BG_MAGENTA, csound.MSG_BG_CYAN, or csound.MSG_BG_GREY.

csound.SetDefaultMessageCallback(function(attributes, string)) sets a function to call when Csound dequeues a default message — a message not associated with a particular instance of Csound — with attributes applied to a string. You can determine the type, text color, and background color of the attributes by performing a bitwise AND with csound.MSG_TYPE_MASK, csound.MSG_FG_COLOR_MASK, and csound.MSG_BG_COLOR_MASK respectively. It’s up to you to decide how to apply attributes to the string. For example, you might use the ansi-styles package to log styled strings to the console.

csound.SetMessageCallback(Csound, function(attributes, string)) sets a function to call when a particular instance of Csound dequeues a message with attributes applied to a string. This function is called in addition to a function you pass to csound.SetDefaultMessageCallback.

csound.CreateMessageBuffer(Csound[, writesToStandardStreams]) prepares a message buffer for retrieving Csound messages using csound.GetMessageCnt, csound.GetFirstMessage, csound.GetFirstMessageAttr, and csound.PopFirstMessage instead of csound.SetMessageCallback. You can retrieve messages from a buffer like this:

const csound = require('csound-api');
const Csound = csound.Create();
csound.CreateMessageBuffer(Csound);
csound.Message(Csound, 'hello, world'); // Add a message to the buffer. 
while (csound.GetMessageCnt(Csound) > 0) {
  console.log(csound.GetFirstMessage(Csound));
  csound.PopFirstMessage(Csound);
}
csound.DestroyMessageBuffer(Csound);
csound.Destroy(Csound);

You can write Csound messages to standard streams in addition to the message buffer by passing true as the second argument. You should call csound.DestroyMessageBuffer when you’re finished with the message buffer.

string = csound.GetFirstMessage(Csound) gets the string of the first message on a message buffer.

attributes = csound.GetFirstMessageAttr(Csound) gets the attributes of the first message on a message buffer. The value of attributes is a bit mask like the one passed to the function argument of csound.SetDefaultMessageCallback.

csound.PopFirstMessage(Csound) removes the first message from a message buffer.

messageCount = csound.GetMessageCnt(Csound) gets the number of messages on a message buffer.

csound.DestroyMessageBuffer(Csound) frees resources used by a message buffer created using csound.CreateMessageBuffer.


Channels, Control & Events

channelCount = csound.ListChannels(Csound, array) sets the contents of the array to objects describing communication channels available in Csound, returning the new length of the array or a negative error code. When you’re finished with the array, you should pass it to csound.DeleteChannelList. The objects added to the array have these read-only properties:

name
is the name of the channel. You can use this name with csound.GetControlChannel and csound.SetControlChannel; and the chn_*, chnexport, chnget, chnparams, and chnset opcodes.
type
is a bit mask of
  • a channel type specified by one of csound.CONTROL_CHANNEL, csound.AUDIO_CHANNEL, csound.STRING_CHANNEL, or csound.PVS_CHANNEL;
  • the input specifier csound.INPUT_CHANNEL; and
  • the output specifier csound.OUTPUT_CHANNEL.
You can determine the channel type by performing a bitwise AND with csound.CHANNEL_TYPE_MASK.
hints
is an object with the same properties as the object you obtain from csound.GetControlChannelHints.

csound.DeleteChannelList(Csound, array) frees resources associated with an array passed to csound.ListChannels.

status = csound.GetControlChannelHints(Csound, name, hints) gets the hints of a control channel named name. When this function returns, the hints object will have properties you can use in a user interface:

behav
is a number indicating how the channel should behave.
When behav equalsThe channel uses
csound.CONTROL_CHANNEL_INTinteger values
csound.CONTROL_CHANNEL_LINreal numbers on a linear scale
csound.CONTROL_CHANNEL_EXPreal numbers on an exponential scale
dflt
is the channel’s default value.
min
is the channel’s minimum value.
max
is the channel’s maximum value.
x
is the preferred x-coordinate for the channel’s user interface.
y
is the preferred y-coordinate for the channel’s user interface.
width
is the preferred width for the channel’s user interface.
height
is the preferred height for the channel’s user interface.
attributes
is a string of attributes for the channel.

You must set the hints of a control channel using csound.SetControlChannelHints before using this function. The returned status is a Csound status code.

status = csound.SetControlChannelHints(Csound, name, hints) sets the hints of the control channel named name. For example,

const csound = require('csound-api');
const Csound = csound.Create();
csound.SetOption(Csound, '--nosound');
const name = 'Channel';
csound.CompileOrc(Csound, `chn_k "${name}", 1`);
if (csound.Start(Csound) === csound.SUCCESS) {
  csound.SetControlChannelHints(Csound, name, {
    behav: csound.CONTROL_CHANNEL_INT,
    attributes: '==> attributes'
  });
  const hints = {};
  csound.GetControlChannelHints(Csound, name, hints);
  console.log(hints.attributes);
}

logs attributes of the control channel named Channel. Note that the hints object you pass to this function must have a behav property set to csound.CONTROL_CHANNEL_INT, csound.CONTROL_CHANNEL_LIN, or csound.CONTROL_CHANNEL_EXP. The returned status is a Csound status code.

number = csound.GetControlChannel(Csound, name[, info]) gets the value of the control channel named name. If you pass an info object to this function, when this function returns the object will have a status property set to a Csound status code.

csound.SetControlChannel(Csound, name, number) sets the value of the control channel named name to a number.

status = csound.ScoreEvent(Csound, eventType[, parameterFieldValues]) sends a score event to Csound. The eventType string can be 'a', 'e', 'f', 'i', or 'q'; and parameterFieldValues is an optional array of numeric parameters for the score event. Note that this means you cannot use csound.ScoreEvent to activate an instrument by name. The returned status is a Csound status code.

csound.InputMessage(Csound, scoreStatement) sends a score statement string to Csound.


Tables

length = csound.TableLength(Csound, functionTableID) gets the length of the function table with functionTableID. The functionTableID is parameter 1 of a score f statement.

numberAtIndex = csound.TableGet(Csound, functionTableID, index) gets the value of the function table with functionTableID at the specified index. The index must be less than the function table’s length.

csound.TableSet(Csound, functionTableID, index, number) sets the value at the specified index of the function table with functionTableID to number. The index must be less than the function table’s length.


Function Table Display

wasGraphable = csound.SetIsGraphable(Csound, isGraphable) sets a Boolean indicating whether csound.SetMakeGraphCallback and csound.SetDrawGraphCallback are called, and returns the previous value. Note that you must set callback functions using both csound.SetMakeGraphCallback and csound.SetDrawGraphCallback for either callback function to be called.

csound.SetMakeGraphCallback(Csound, function(data, name)) sets a function for Csound to call when it first makes a graph of a function table or other data series. The function is passed a data object and the name of the graph as a string. Note that you must pass true to csound.SetIsGraphable and also set a callback function using csound.SetDrawGraphCallback for this function to be called. The data object passed to the function has these read-only properties:

windid
is an arbitrary numeric identifier for the graph.
caption
is a string describing the graph.
max
is the maximum of the fdata property.
min
is the minimum of the fdata property.
oabsmax
is a scale factor for the vertical axis.
fdata
is the data to be graphed as an array of numbers.

csound.SetDrawGraphCallback(Csound, function(data)) sets a function for Csound to call when it draws a graph of a function table or other data series. The function is passed a data object with the same properties as the one passed to the function argument of csound.SetMakeGraphCallback. Note that you must pass true to csound.SetIsGraphable and also set a callback function using csound.SetMakeGraphCallback for this function to be called.


Opcodes

opcodeCount = csound.NewOpcodeList(Csound, array) sets the contents of the array to objects describing opcodes available in Csound, returning the new length of the array or a negative error code. When you’re finished with the array, you should pass it to csound.DisposeOpcodeList. The objects added to the array have these read-only properties:

opname
is the opcode’s name.
outypes
is a string of characters that describe output arguments:
aa‑rate vector
Fcomma-separated list of frequency-domain variables, used by phase vocoder opcodes
mcomma-separated list of a‑rate vectors
Ncomma-separated list of i‑time scalars, k‑rate scalars, a‑rate vectors, and strings
sk‑rate scalar or a‑rate vector
Xcomma-separated list of i‑time scalars, k‑rate scalars, and a‑rate vectors
zcomma-separated list of k‑rate scalars
*comma-separated list of arguments of any type
intypes
is a string of characters that describe input arguments:
aa‑rate vector
BBoolean
ffrequency-domain variable, used by phase vocoder opcodes
hoptional i‑time scalar defaulting to 127
ii‑time scalar
joptional i‑time scalar defaulting to –1
Joptional k‑rate scalar defaulting to –1
kk‑rate scalar
llabel, used by goto opcodes
mcomma-separated list of any number of i‑time scalars
Mcomma-separated list of i‑time scalars, k‑rate scalars, and a‑rate vectors
ncomma-separated list of an odd number of i‑time scalars
Ncomma-separated list of i‑time scalars, k‑rate scalars, a‑rate vectors, and strings
ooptional i‑time scalar defaulting to 0
Ooptional k‑rate scalar defaulting to 0
poptional i‑time scalar defaulting to 1
Poptional k‑rate scalar defaulting to 1
qoptional i‑time scalar defaulting to 10
Sstring
Ti‑time scalar or string
Ui‑time scalar, k‑rate scalar, or string
voptional i‑time scalar defaulting to 0.5
Voptional k‑rate scalar defaulting to 0.5
wfrequency-domain variable, used by spectrum and related opcodes
Wcomma-separated list of strings
xk‑rate scalar or a‑rate vector
ycomma-separated list of a‑rate vectors
zcomma-separated list of k‑rate scalars
Zcomma-separated list of alternating k‑rate scalars and a‑rate vectors
.required argument of any type
?optional argument of any type
*comma-separated list of arguments of any type

csound.DisposeOpcodeList(Csound, array) frees resources associated with an array passed to csound.NewOpcodeList.


Miscellaneous Functions

environmentVariableValue = csound.GetEnv(Csound, environmentVariableName) gets the string value of a Csound environment variable named environmentVariableName.

status = csound.SetGlobalEnv(environmentVariableName, value) sets the value of a Csound environment variable named environmentVariableName to string value.


Status Codes

A number of csound-api functions return csound.SUCCESS upon successful completion, or one of these error codes:

  • csound.ERROR
  • csound.INITIALIZATION
  • csound.PERFORMANCE
  • csound.MEMORY
  • csound.SIGNAL

Tests

The tests of this package require Jasmine. To install the Jasmine package globally, run

npm --global install jasmine

To run the tests, cd to the csound-api folder (which should be in node_modules if you installed csound-api locally) and run jasmine.

On macOS

To run the Jasmine tests in Xcode:

  1. cd to the csound-api folder and run

    node-gyp rebuild --debug && node-gyp configure -- -f xcode

    to create a debug version of csound-api and an Xcode project at csound-api/build/binding.xcodeproj.

  2. Open the Xcode project, choose Product > Scheme > Edit Scheme or press Command-< to open the scheme editor, and select Run in the list on the left.

  3. In the Info tab, select Other from the Executable pop-up menu, press Command-Shift-G, enter the path to the Node.js executable in the dialog that appears, click Go, and then click Choose. The Node.js executable is usually at /usr/local/bin/node, and you can determine the path to the Node.js executable by running which node in Terminal.

  4. In the Arguments tab, add Jasmine’s path to the Arguments Passed On Launch. If you installed Jasmine globally, you can determine Jasmine’s path by running which jasmine in Terminal. You may also want to add a --no-colors argument so that ANSI escape codes don’t appear in Xcode’s Console.

  5. Add an environment variable named JASMINE_CONFIG_PATH with a value of the relative path from Node.js to the csound-api test script. To quickly determine this path, cd to the csound-api folder and run

    python -c "import os; print(os.path.relpath('$(pwd)/spec/csound-api-spec.js', os.path.realpath('$(which node)')))"
  6. Close the scheme editor, and then choose Product > Run or press Command-R to run csound-api’s tests in Xcode.

On Windows

To run the Jasmine tests in Visual Studio:

  1. cd to the csound-api folder and run

    node-gyp rebuild --debug && node-gyp configure -- -f msvs

    to create a debug version of csound-api and a Visual Studio solution at csound-api/build/binding.sln.

  2. Open the Visual Studio solution, select the csound-api project in the Solution Explorer, press Alt-Enter to open the csound-api Property Pages, select C/C++ in the list on the left, and add the path to Boost to the semicolon-separated list of Additional Include Directories.

  3. Choose File > Add > Existing Project, select the Node.js executable in the dialog that appears, and then click Open. The Node.js executable is usually at C:\Program Files\nodejs\node.exe, and you can determine the path to the Node.js executable by running where node in Command Prompt.

  4. Right-click the Node.js executable in the Solution Explorer and select Set as StartUp Project in the menu that appears. Then, press Alt-Enter to view the Node.js executable’s properties.

  5. Set the Arguments to Jasmine’s path, enclosed in quotes. If you installed Jasmine globally, this is usually the output of running in Command Prompt

    echo "%APPDATA%\npm\node_modules\jasmine\bin\jasmine.js"
  6. Add an environment variable named JASMINE_CONFIG_PATH with a value of the relative path from Node.js to the csound-api test script. To quickly determine this path, cd to the csound-api folder and run

    python -c "import os, subprocess; print(os.path.relpath(os.path.join(os.getcwd(), 'spec', 'csound-api-spec.js'), subprocess.check_output(['where', 'node'])))"
  7. Choose Debug > Start Debugging or press F5 to run csound-api’s tests in Visual Studio.