Skip to content

nwhetsell/csound-api

Repository files navigation

Csound API

Actions npm npm

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');

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 and Csound is probably through Homebrew. To install Homebrew, follow the instructions at https://brew.sh. Then, enter in Terminal:

brew install boost csound

When installing Csound, Homebrew may output this error message:

Error: The `brew link` step did not complete successfully
The formula built, but is not symlinked into /usr/local
Could not symlink bin/atsa
Target /usr/local/bin/atsa
already exists. You may want to remove it:
  rm '/usr/local/bin/atsa'

To force the link and overwrite all conflicting files:
  brew link --overwrite csound

To list all files that would be deleted:
  brew link --overwrite --dry-run csound

This error occurs when Csound is already installed from a disk image available at https://github.com/csound/csound/releases. To resolve this error, follow the instructions in the error message.

After you install Boost and Csound, you can install this package by entering in Terminal:

export CPATH="$(brew --prefix)/include"
export LIBRARY_PATH="$(brew --prefix)/lib"
npm install csound-api

On Linux

On many Linux distributions, you can install Boost and Csound by entering:

sudo apt-get --assume-yes install libboost-dev libcsound64-dev

You can then install this package by entering:

npm install csound-api

On Linux, this package depends on a Csound shared object (.so) file. This file is named libcsound64.so when Csound is compiled to use double-precision samples, and libcsound.so when Csound is compiled to use single-precision samples. (The 64 in libcsound64 refers to the number of bits in a double-precision sample, not computer architecture.) This package depends on libcsound64.so, not libcsound.so. If an error about a missing libcsound64.so file occurs when installing this package, it probably means your version of Csound uses single-precision samples.

On Windows

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.

You must also follow the steps at https://github.com/nodejs/node-gyp#on-windows.

You can then install this package by entering in PowerShell:

$Env:CL = '/I"C:\path\to\boost" /I"C:\path\to\csound\include"'
$Env:LINK = '"C:\path\to\csound\lib\csound64.lib"'
npm install csound-api

or in Command Prompt:

set CL=/I"C:\path\to\boost" /I"C:\path\to\csound\include"
set LINK="C:\path\to\csound\lib\csound64.lib"
npm install csound-api

where C:\path\to\boost is the path to Boost and C:\path\to\csound is the path to Csound (usually C:\Program Files\csound).

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');

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 1000. For example, if you’re using Csound 6.13, versionTimes1000 will be 6130.

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

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 these read-only properties:

PropertyDescription
type 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

An Object describing the token with several read-only properties:

PropertyDescription
type A Number indicating the type of token. This may not be the same as the type of the AST object.
lexeme A String, usually the string value of the token, but not always. For example, operator opcodes like + have lexemes like ##add.
value A Number equal to the value of the token if it’s an integer, and 0 otherwise.
fvalue A Number equal to the value of the token if it’s a floating-point number, and 0 otherwise.
line A Number indicating the line where the token occurs.
left An AST node that generally represents the first output argument of an opcode.
right An AST node that generally represents the first input argument of an opcode.
next

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.


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 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.


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/.


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.


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

  • 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.


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:

PropertyDescription
name The name of the channel as a String. You can use this name with csound.GetControlChannel and csound.SetControlChannel; and the chn_*, chnexport, chnget, chnparams, and chnset opcodes.
type

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
  • the output specifier csound.OUTPUT_CHANNEL

You can determine the channel type by performing a bitwise AND with csound.CHANNEL_TYPE_MASK.

hints 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:

PropertyDescription
behav

A Number indicating how the channel should behave:

When behav equalsThe channel uses
csound.CONTROL_CHANNEL_INT integer values
csound.CONTROL_CHANNEL_LIN real numbers on a linear scale
csound.CONTROL_CHANNEL_EXP real numbers on an exponential scale
dflt A Number giving the channel’s default value.
min A Number giving the channel’s minimum value.
max A Number giving the channel’s maximum value.
x A Number giving the preferred x-coordinate for the channel’s user interface.
y A Number giving the preferred y-coordinate for the channel’s user interface.
width A Number giving the preferred width for the channel’s user interface.
height A Number giving the preferred height for the channel’s user interface.
attributes 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. (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.


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.


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:

PropertyDescription
windid An arbitrary Number identifying the graph.
caption A String describing the graph.
max A Number giving the maximum of the fdata property.
min A Number giving the minimum of the fdata property.
oabsmax A Number giving a scale factor for the vertical axis.
fdata 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.


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:

PropertyDescription
opname The opcode’s name as a String.
outypes

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

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.


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 install --global 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 to the Arguments Passed On Launch:

    1. Jasmine’s path (if you installed Jasmine globally, you can determine Jasmine’s path by running which jasmine in Terminal)
    2. --config=/path/to/csound-api-spec.js, where /path/to/csound-api-spec.js is the path to csound-api-spec.js.
    3. --no-color
    4. --random=false
    5. --reporter=/path/to/reporter.js, where /path/to/reporter.js is the path to reporter.js.
  5. 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 PowerShell or 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 PowerShell:

    "$Env:APPDATA\npm\node_modules\jasmine\bin\jasmine.js"

    or 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.