Class Chuck

WebChucK extends the Web Audio AudioWorkletNode class and provides an interface to interact with the ChucK Virtual Machine. Use init() to create a ChucK instance.

theChuck is a global variable that is used in the examples below. init() will create a ChucK instance and an AudioContext if one is not provided.

import { Chuck } from "webchuck";

let theChuck; // global variable

document.getElementById("start").addEventListener("click", async () => {
if (theChuck === undefined) {
theChuck = await Chuck.init([]);
}
theChuck.runCode("SinOsc osc => dac; 1::second => now;");
});

Note that many browsers do not let audio run until there has been user interaction (e.g. button press). You can check for a suspended audio context and resume like this:

if (theChuck.context.state === "suspended") {
theChuck.context.resume();
}

Hierarchy

  • AudioWorkletNode
    • Chuck

Constructors

  • Private internal constructor for a ChucK AudioWorklet Web Audio Node. Use public Init to create a ChucK instance.

    Parameters

    • preloadedFiles: File[]

      Array of Files to preload into ChucK's filesystem

    • audioContext: AudioContext

      AudioContext to connect to

    • wasm: ArrayBuffer

      WebChucK WebAssembly binary

    • numOutChannels: number = 2

      Number of output channels

    Returns Chuck

    ChucK AudioWorklet Node

Properties

deferredPromises: DeferredPromisesMap = {}
deferredPromiseCounter: number = 0
eventCallbacks: EventCallbacksMap = {}
eventCallbackCounter: number = 0
isReady: default<void> = ...
chugins: string[] = []
onprocessorerror: null | ((this, ev) => any)

Type declaration

    • (this, ev): any
    • Parameters

      • this: AudioWorkletNode
      • ev: Event

      Returns any

parameters: AudioParamMap
port: MessagePort
channelCount: number
channelCountMode: ChannelCountMode
channelInterpretation: ChannelInterpretation
context: BaseAudioContext
numberOfInputs: number
numberOfOutputs: number

Methods

  • Initialize a ChucK AudioWorkletNode. By default, a new AudioContext is created and ChucK is connected to the AudioContext destination. Note: init() is overloaded to allow for a custom AudioContext, custom number of output channels, and custom URL location of whereIsChuck. Skip an argument by passing in undefined.

    Parameters

    • filenamesToPreload: Filename[]

      Array of auxiliary files to preload into ChucK's filesystem. These can be .wav files, .ck files, .etc. [{serverFilename: "./path/filename.wav", virtualFilename: "filename.wav"}...]

    • Optional audioContext: AudioContext

      Optional parameter if you want to use your own AudioContext. Note: If an AudioContext is passed in, you will need to connect the ChucK instance to your own destination.

    • numOutChannels: number = 2

      Optional custom number of output channels. Default is 2 channel stereo and the Web Audio API supports up to 32 channels.

    • whereIsChuck: string = "https://chuck.stanford.edu/webchuck/src/"

      Optional custom url to your WebChucK src folder containing webchuck.js and webchuck.wasm. By default, whereIsChuck is here.

    Returns Promise<Chuck>

    WebChucK ChucK instance

    Example

    // default initialization
    theChuck = await Chuck.init([]);

    Example

    // Initialize ChucK with a list of files to preload
    theChuck = await Chuck.init([{serverFilename: "./path/filename.wav", virtualFilename: "filename.wav"}...]);

    Example

    // Initialize ChucK with a local audioContext, connect ChucK to the context destination
    var audioContext = new AudioContext();
    theChuck = await Chuck.init([], audioContext));
    theChuck.connect(audioContext.destination);

    Example

    // Initialize ChucK using local webchuck.js and webchuck.wasm files in "./src"
    theChuck = await Chuck.init([], undefined, undefined, "./src");
  • Load a single WebChugin (.chug.wasm) via url into WebChucK. A list of publicly available WebChugins to load can be found in the webchugins folder. Call this per chugin that you want to load. Note: WebChugins must be loaded before theChuck is initialized.

    Parameters

    • url: string

      URL to webchugin to load

    Returns void

    Example

    Chuck.loadChugin("https://url/to/myChugin.chug.wasm");
    theChuck = await Chuck.init([]);
  • Private function for ChucK to handle execution of tasks. Will create a Deferred promise that wraps a task for WebChucK to execute

    Returns number

    callbackID to a an action for ChucK to perform

  • Create a virtual file in ChucK's filesystem. You should first locally fetch the contents of your file, then pass the data to this method. Alternatively, you can use loadFile to automatically fetch and load a file from a URL.

    Parameters

    • directory: string

      Virtual directory to create file in

    • filename: string

      Name of file to create

    • data: string | ArrayBuffer

      Data to write to the file

    Returns void

  • Create a virtual directory in ChucK's filesystem.

    Parameters

    • parent: string

      Virtual directory to create the new directory in

    • name: string

      Name of directory to create

    Returns void

  • Automatically fetch and load in a file from a URL to ChucK's virtual filesystem

    Parameters

    • url: string

      Path or url to a file to fetch and load file

    Returns Promise<void>

    Promise of fetch request

    Example

    theChuck.loadFile("./myFile.ck");
    
  • Return a list of loaded WebChugins.

    Returns string[]

    String array of loaded WebChugin names

  • Run a string of ChucK code.

    Parameters

    • code: string

      ChucK code string to be executed

    Returns Promise<number>

    Promise to shred ID

    Example

    theChuck.runCode("SinOsc osc => dac; 1::second => now;");
    
  • Replace the last currently running shred with string of ChucK code to execute.

    Parameters

    • code: string

      ChucK code string to run and replace last shred

    Returns Promise<{
        oldShred: number;
        newShred: number;
    }>

    Promise to shred ID that is replaced

    Example

    theChuck.replaceCode("SinOsc osc => dac; 1::second => now;");
    
  • Remove the last running shred from Chuck Virtual Machine.

    Returns Promise<number>

    Promise to the shred ID that was removed

  • Run a ChucK file that is already loaded in the WebChucK virtual file system. Note that the file must already have been loaded via filenamesToPreload, createFile, or loadFile

    Parameters

    • filename: string

      ChucK file to be run

    Returns Promise<number>

    Promise to running shred ID

    Example

    await theChuck.loadFile("./myFile.ck"); // wait for file to load
    theChuck.runFile("myFile.ck");
  • Run a ChucK file already loaded in the WebChucK virtual file system and pass in arguments. e.g. Thie is the chuck command line equivalent of chuck myFile:1:2:foo

    Parameters

    • filename: string

      ChucK file to be run

    • colonSeparatedArgs: string

      Arguments to pass to the file separated by colons

    Returns Promise<number>

    Promise to running shred ID

    Example

    theChuck.runFileWithArgs("myFile.ck", "1:2:foo");
    
  • Replace the last currently running shred with a Chuck file to execute. Note that the file must already have been loaded via filenamesToPreload, createFile, or loadFile

    Parameters

    • filename: string

      File to replace last shred

    Returns Promise<{
        oldShred: number;
        newShred: number;
    }>

    Promise to replaced shred ID

  • Replace the last running shred with a file to execute, passing arguments. Note that the file must already have been loaded via filenamesToPreload, createFile, or loadFile

    Parameters

    • filename: string

      File to be replace last running shred

    • colonSeparatedArgs: string

      Arguments to pass in to file

    Returns Promise<{
        oldShred: number;
        newShred: number;
    }>

    Promise to shred ID

  • Remove a shred from ChucK VM by ID

    Parameters

    • shred: string | number

      Shred ID to be removed

    Returns Promise<number>

    Promise to shred ID if removed successfully, otherwise "removing code failed"

  • Check if shred with ID is running in the Chuck Virtual Machine.

    Parameters

    • shred: string | number

      The shred ID to check

    Returns Promise<number>

    Promise to whether shred is running, 1 if running, 0 if not

  • Signal a ChucK event global. This will wake the first waiting Shred.

    Parameters

    • variable: string

      ChucK global event variable to be signaled

    Returns void

  • Broadcast a ChucK event to all waiting Shreds.

    Parameters

    • variable: string

      ChucK global event variable to be signaled

    Returns void

  • Listen for a specific ChucK event to be signaled (through either signal() or broadcast()). Once signaled, the callback function is invoked. This can happen at most once per call.

    Parameters

    • variable: string

      ChucK global event variable to be signaled

    • callback: (() => void)

      JavaScript callback function

        • (): void
        • Returns void

    Returns void

  • Listen for a specific ChucK event to be signaled (through either signal() or broadcast()). Each time the event is signaled, the callback function is invoked. This continues until stopListeningForEvent is called on the specific event.

    Parameters

    • variable: string

      ChucK global event variable to be signaled

    • callback: (() => void)

      JavaScript callback function

        • (): void
        • Returns void

    Returns number

    JavaScript callback ID

  • Stop listening to a specific ChucK event, undoing the process started by startListeningForEvent.

    Parameters

    • variable: string

      ChucK global event variable to be signaled

    • callbackID: number

      Callback ID returned by startListeningForEvent

    Returns void

  • Set the value of a global int variable in ChucK.

    Parameters

    • variable: string

      Name of int global variable

    • value: number

      New int value to set

    Returns void

    Example

    theChuck.setInt("MY_GLOBAL_INT", 5);
    
  • Get the value of a global int variable in ChucK.

    Parameters

    • variable: string

      Name of int global variable

    Returns Promise<number>

    Promise with int value of the variable

    Example

    const myGlobalInt = await theChuck.getInt("MY_GLOBAL_INT");
    
  • Set the value of a global float variable in ChucK.

    Parameters

    • variable: string

      Name of float global variable

    • value: number

      New float value to set

    Returns void

  • Get the value of a global float variable in ChucK.

    Parameters

    • variable: string

      Name of float global variable

    Returns Promise<number>

    Promise with float value of the variable

  • Set the value of a global string variable in ChucK.

    Parameters

    • variable: string

      Name of string global variable

    • value: string

      New string value to set

    Returns void

  • Get the value of a global string variable in ChucK.

    Parameters

    • variable: string

      Name of string global variable

    Returns Promise<string>

    Promise with string value of the variable

  • Set the values of a global int array in ChucK.

    Parameters

    • variable: string

      Name of global int array variable

    • values: number[]

      Array of numbers to set

    Returns void

  • Get the values of a global int array in ChucK.

    Parameters

    • variable: string

      Name of global int array variable

    Returns Promise<number[]>

    Promise to array of numbers

  • Set a single value (by index) in a global int array in ChucK.

    Parameters

    • variable: string

      Name of int array variable

    • index: number

      Array index to set

    • value: number[]

      Value to set

    Returns void

  • Get a single value (by index) in a global int array in ChucK.

    Parameters

    • variable: string

      Name of int array variable

    • index: number

      Array index to get

    Returns Promise<number>

    Promise to the value at the index

  • Set the value (by key) of an associative int array in ChucK. Note that "associative array" is ChucK's version of a dictionary with string keys mapping to values (see ChucK documentation).

    Parameters

    • variable: string

      Name of global associative int array to set

    • key: string

      The key index (string) of the associative array

    • value: string | number

      The new value

    Returns void

    Example

    theChucK.setAssociativeIntArrayValue("MY_INT_ASSOCIATIVE_ARRAY", "key", 5);
    
  • Get the value (by key) of an associative int array in ChucK. e.g. theChucK.getAssociateIntArrayValue("MY_INT_ASSOCIATIVE_ARRAY", "key");

    Parameters

    • variable: string

      Name of gobal associative int arry

    • key: string

      The key index (string) to get

    Returns Promise<number>

    Promise with int array value

  • Set the values of a global float array in ChucK.

    Parameters

    • variable: string

      Name of global float array

    • values: number[]

      Values to set

    Returns void

  • Get the values of a global float array in ChucK.

    Parameters

    • variable: string

      Name of float array

    Returns Promise<number[]>

    Promise of float values

    Example

    theChucK.getFloatArray("MY_FLOAT_ARRAY");
    
  • Set the float value of a global float array at particular index.

    Parameters

    • variable: string

      Name of global float array

    • index: number

      Index of element

    • value: number

      Value to set

    Returns void

  • Get the float value of a global float arry at a particular index.

    Parameters

    • variable: string

      Name of global float array

    • index: number

      Index of element

    Returns Promise<number>

    Promise of float value at index

    Example

    theChucK.getFloatArray("MY_FLOAT_ARRAY", 1);
    
  • Set the value (by key) of an associative float array in ChucK. Note that "associative array" is ChucK's version of a dictionary with string keys mapping to values (see ChucK documentation).

    Parameters

    • variable: string

      Name of global associative float array to set

    • key: string

      The key index (string) of the associative array

    • value: number

      Float value to set

    Returns void

    Example

    theChucK.setAssociateFloatArrayValue("MY_FLOAT_ASSOCIATIVE_ARRAY", "key", 5);
    
  • Get the value (by key) of an associative float array in ChucK.

    Parameters

    • variable: string

      Name of gobal associative float array

    • key: string

      The key index (string) to get

    Returns Promise<number>

    Promise with float array value

    Example

    theChucK.getAssociateFloatArrayValue("MY_FLOAT_ASSOCIATIVE_ARRAY", "key");
    
  • Set an internal ChucK VM integer parameter. e.g. "SAMPLE_RATE", "INPUT_CHANNELS", "OUTPUT_CHANNELS", "IS_REAL_TIME_AUDIO_HINT", "TTY_COLOR".

    Parameters

    • name: string

      Name of VM int parameter to set

    • value: number

      Value to set

    Returns void

  • Get an internal ChucK VM integer parameter. e.g. "SAMPLE_RATE", "INPUT_CHANNELS", "OUTPUT_CHANNELS", "BUFFER_SIZE", "IS_REAL_TIME_AUDIO_HINT".

    Parameters

    • name: string

      Name of VM int parameter to get

    Returns Promise<number>

    Promise with int value

  • Set an internal ChucK VM float parameter.

    Parameters

    • name: string

      Name of VM float parameter to set

    • value: number

      Value to set

    Returns void

  • Get an internal ChucK VM float parameter.

    Parameters

    • name: string

      Name of VM float parameter to get

    Returns Promise<number>

    Promise with float value

  • Set an internal ChucK VM string parameter.

    Parameters

    • name: string

      Name of VM string parameter to set

    • value: string

      Value to set

    Returns void

  • Get an internal ChucK VM string parameter. e.g. "VERSION".

    Parameters

    • name: string

      Name of VM string parameter to get

    Returns Promise<string>

    Promise with string value

  • Get the current time in samples of the ChucK VM.

    Returns Promise<number>

    Promise to current sample time in ChucK (int)

  • Remove all shreds and reset the ChucK instance.

    Returns void

  • Reset all global variables in ChucK.

    Returns void

  • Callback function for Chuck to print a message string to console. Override this method to redirect where ChucK console output goes. By default, Chuck prints to console.log(). Set your own method to display ChucK output or even use ChucK output as a message passing system.

    Parameters

    • message: string

      Message that ChucK will print to console

    Returns void

    Example

    // Override the default print method with our own callback print method
    theChuck.chuckPrint = (message) => { console.log("ChucK says: " + message); }

    // Now when ChucK prints, it will print to our callback method
    theChuck.runCode(`<<< "Hello World!", "" >>>`);

    // Output: "ChucK says: Hello World!"
  • Type Parameters

    • K extends "processorerror"

    Parameters

    • type: K
    • listener: ((this, ev) => any)
        • (this, ev): any
        • Parameters

          • this: AudioWorkletNode
          • ev: AudioWorkletNodeEventMap[K]

          Returns any

    • Optional options: boolean | AddEventListenerOptions

    Returns void

  • Parameters

    • type: string
    • listener: EventListenerOrEventListenerObject
    • Optional options: boolean | AddEventListenerOptions

    Returns void

  • Type Parameters

    • K extends "processorerror"

    Parameters

    • type: K
    • listener: ((this, ev) => any)
        • (this, ev): any
        • Parameters

          • this: AudioWorkletNode
          • ev: AudioWorkletNodeEventMap[K]

          Returns any

    • Optional options: boolean | EventListenerOptions

    Returns void

  • Parameters

    • type: string
    • listener: EventListenerOrEventListenerObject
    • Optional options: boolean | EventListenerOptions

    Returns void

  • Parameters

    • destinationNode: AudioNode
    • Optional output: number
    • Optional input: number

    Returns AudioNode

  • Parameters

    • destinationParam: AudioParam
    • Optional output: number

    Returns void

  • Returns void

  • Parameters

    • output: number

    Returns void

  • Parameters

    • destinationNode: AudioNode

    Returns void

  • Parameters

    • destinationNode: AudioNode
    • output: number

    Returns void

  • Parameters

    • destinationNode: AudioNode
    • output: number
    • input: number

    Returns void

  • Parameters

    • destinationParam: AudioParam

    Returns void

  • Parameters

    • destinationParam: AudioParam
    • output: number

    Returns void

  • Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise.

    Parameters

    • event: Event

    Returns boolean