Class: Web Audio Helpers

Web Audio API tools

When running in the browser, Superpowered sits on top of the Web Audio API's AudioContext. The AudioContext manages the streams to and from the computers audio hardware and also schedules the audio processing callback which we use to render our audio buffers with the Superpowered WebAssembly library.

We've created some helpers which will help you get audio up and running.

For a complete guide to getting setup, you may want to take a look at our guide:


SuperpoweredGlue

SuperpoweredGlue helps you fetch and initialize the Superpowered WebAssembly library you'll be using throughout your application. It creates all the convenient, but also efficient interfaces you can use with Javascript. A WebAssembly interface doesn't even have classes, but this glue creates the plumbing for the Superpowered API. Once initialized, the instantiated Superpowered object is made available for use inside the Javascript context you use.

// Importing in javascript main application (bundled)
// Most common: import Superpowered and the Superpowered Web Audio helper:
import { SuperpoweredGlue } from './superpowered/SuperpoweredWebAudio.js';
// Importing inside a Worker script
// Most major web browsers can not import modules in Worker scripts, therefore the import above may not work so al.
importScripts('./superpowered/SuperpoweredGlue.js');
// Create a SuperpoweredGlue instance and fetch the Superpowered WebAssembly from a publicly accessible location on the web. This happens at runtime, not build!
var Superpowered = await SuperpoweredGlue.fetch('./superpowered/superpowered.wasm');
// We must now initialize the Superpowered WebAssembly.
// Insert your license key here or use the one provided below for evaluation.
Superpowered.Initialize('ExampleLicenseKey-WillExpire-OnNextUpdate');

SuperpoweredWebAudio

We've wrapped the standard AudioContext class with some helpers to streamline some common tasks when writing audio web applications. The SuperpoweredWebAudio class contains helper functions for easier Web Audio initialization. The returned objects are standard Web Audio objects without any quirks.

Please note that to enable Web Audio features on a page, you are required to be running from a secure context: HTTPS or localhost.

audioContext

PROPERTY
A standard AudioContext.
TypeMinMaxDefault
AudioContext
  • constructor

    METHOD
    Creates an instance of the SupowereedWebAudio class.
    Parameters
    NameTypeDescription
    samplerateNumberThe initial sample rate in Hz.
    SuperpoweredNumberAn initialised Superpowered instance.
    Returns
    TypeDescription
    Superpowered.WebAudioManagerA Superpowered WebAudioManager
  • createAudioNode

    METHOD

    Creates an Audio Worklet (for new browsers) or an audio processing ScriptProcessorNode (for older browsers).

    This function was made to help with browser-specific quirks and to properly initialize Superpowered in an Audio Worklet context.

    Parameters
    NameTypeDescription
    urlNumberThe publicly accessible AudioWorkletProcessor module.
    nameNumberThe name of the Processor you have registered within your AudioWorkletProcessor script (case-sensitive)
    onSuccessNumberRuns after the audio node is created. Single argument `newNode`, which is a standard AudioNode or a ScriptProcessorNode for use in your WebAudio graph.
    onMessageFromAudioScopeNumberIs called whenever `sendMessageToAudioScope` is called from the within the AudioWorkletProcessor. Single argument `message` provided.
    Returns
    None
  • createAudioNodeAsync

    METHOD

    Creates an Audio Worklet (for new browsers) or an audio processing ScriptProcessorNode (for older browsers).

    This function was made to help with browser-specific quirks and to properly initialize Superpowered in an Audio Worklet context.

    Parameters
    NameTypeDescription
    urlNumberThe publicly accessible AudioWorkletProcessor module.
    nameNumberThe name of the Processor you have registered within your AudioWorkletProcessor script (case-sensitive)
    onSuccessNumberRuns after the audio node is created. Single argument `newNode`, which is a standard AudioNode or a ScriptProcessorNode for use in your WebAudio graph.
    onMessageFromAudioScopeNumberIs called whenever `sendMessageToAudioScope` is called from the within the AudioWorkletProcessor. Single argument `message` provided.
    Returns
    TypeDescription
    NumberA standard AudioNode or ScriptProcessorNode for use in a Web Audio graph.
  • destruct

    METHOD

    Will return false from the process() method of the AudioWorkletNode and run onDestruct within the associated AudioWorkletProcessor, to help you clean up your class instances.

    Parameters
    None
    Returns
    None
  • getUserMediaForAudio

    METHOD

    Prompts the user for permission to use a media input (typically the microphone) with an audio track and no video tracks.

    This function was made to help with browser-specific quirks, see here.

    Parameters
    NameTypeDescription
    mediaConstraintsNumber

    See here for more information about MediaContraints.

    onSuccessNumberCallback on successful audio capture. Single argument `stream` provided.
    onErrorNumberCallback on unsuccessful audio capture. Single argument `error` provided.
    Returns
    None
  • getUserMediaForAudioAsync

    METHOD
    Asynchronous version of getUserMediaForAudio.
    Parameters
    NameTypeDescription
    mediaConstraintsNumber

    See here for more information about MediaContraints.

    Returns
    TypeDescription
    NumberReturns with a standard MediaStream object or undefined on error.

Code examples

var webaudioManager = new SuperpoweredWebAudio(
44100, // The minimum sample rate of the AudioContext. The actual sample rate may be equal or higher.
Superpowered // The SuperpoweredGlue instance.
);
// Returns with a standard AudioContext. Reference: https://developer.mozilla.org/en-US/docs/Web/API/AudioContext
let audioContext = webaudioManager.audioContext;
// Prompts the user for permission to use a media input (typically the microphone) with an audio track and no video tracks. Has no return value.
// This function was made to help with browser-specific quirks.
// Reference https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia
webaudioManager.getUserMediaForAudio(
{ // navigator.mediaDevices.getUserMedia constraints
'echoCancellation': false
},
function(stream) {
// Called when the user provided permission (for the microphone).
// stream is a standard MediaStream object:
// https://developer.mozilla.org/en-US/docs/Web/API/MediaStream
},
function(error) {
// Called when the user refused the (microphone) permission.
// Visit the reference above on what error represents.
}
);
// Asynchronous version of getUserMediaForAudio.
// Returns with a standard MediaStream object or undefined on error.
let audioInputStream = await webaudioManager.getUserMediaForAudioAsync(
{ // navigator.mediaDevices.getUserMedia constraints or "fastAndTransparentAudio" to disable all processing on the audio input
'fastAndTransparentAudio': true
},
)
.catch((error) => {
// Called when the user provided permission (typically for the microphone).
});
if (!audioInputStream) return; // Program flow will reach this point even on error.
// Creates an Audio Worklet (for new browsers) or an audio processing ScriptProcessorNode (for older browsers).
// This function was made to help with browser-specific quirks and to properly initialize Superpowered in an Audio Worklet context.
var myAudioNode = null;
webaudioManager.createAudioNode(
'/example_effects/processor.js', // The JavaScript module source of the node.
'MyProcessor', // The registered processor name.
function(newNode) {
// Runs after the audio node is created.
// newNode is a standard AudioNode or a ScriptProcessorNode.
myAudioNode = newNode;
},
function(message) {
// Runs in the main scope (main thread) when the audio node sends a message.
// message is a standard JavaScript object.
// Let's send some data to the audio scope (audio thread).
// This method accepts any object (string, array, etc.) as it's single input parameter.
myAudioNode.sendMessageToAudioScope({
someText: "Hey!"
});
}
);
// Asynchronous version of createAudioNode.
// Returns with a standard AudioNode or ScriptProcessorNode.
let audioNode = await webaudioManager.createAudioNodeAsync(
audioContext, // The standard AudioContext instance.
'/example_effects/processor.js', // The JavaScript module source of the node.
'MyProcessor', // The registered processor name.
function(message) {
// Runs in the main scope (main thread) when the audio node sends a message.
// message is a standard JavaScript object.
}
);
// Will return false from the process() method of the AudioWorkletNode and run onDestruct to clean up WebAssembly and more.
audioNode.destruct();

AudioWorkletProcessor

The easiest way to use Superpowered features in a Web Audio AudioNode is the SuperpoweredWebAudio.AudioWorkletProcessor class.

It can be created by createAudioNode (see the example above) and should be loaded from a dedicated .js file, because it's a JS module in modern browsers.

class MyProcessor extends SuperpoweredWebAudio.AudioWorkletProcessor {
onReady() {
// Runs after the constructor. This is "your" constructor basically.
}
onDestruct() {
// Runs before the node is destroyed.
// Clean up memory and objects here (such as free allocated linear memory or destruct Superpowered objects).
}
onMessageFromMainScope(message) {
// Runs when a message (data) is received from the main scope (main thread).
// Let's figure out the samplerate we're working with.
let samplerate = this.Superpowered.samplerate;
// Let's send some data back to the main scope (main thread).
// This method accepts any object (string, array, etc.) as it's single input parameter.
this.sendMessageToMainScope({
someText: "Got your message!",
hz: samplerate
});
}
processAudio(inputBuffer, outputBuffer, buffersize, parameters) {
// The audio processing callback running in the audio thread.
// buffersize is the current number of frames, typically 128.
// parameters is a map of string keys and associated Float32Arrays, as standardized by W3:
// https://www.w3.org/TR/webaudio/#AudioNode-methods (see the process() method)
// parameters are not very useful here, because they don't work for older browsers with ScriptProcessorNode.
// Superpowered objects are automatically smoothing parameter changes as required, so there is no need to use the AudioParam features of Web Audio.
// Use sendMessageToAudioScope() to send parameters instead, as you can find in the example projects.
// inputBuffer and outputBuffer contain stereo interleaved 32-bit floating point audio.
// They have both direct WASM linear memory index (pointer) access and JavaScript Float32Array access.
// Typically, Superpowered objects require direct WASM linear memory indexes (pointers) for audio input and/or output:
SomeSuperpoweredObject.process(inputBuffer.pointer, outputBufer.pointer, buffersize);
// Direct JavaScript Float32Array access to audio input and/or output:
let firstInputSampleLeft = inputBuffer.array[0];
let firstInputSampleRight = inputBuffer.array[1];
outputBuffer.array[0] = firstInputSampleLeft;
outputBuffer.array[1] = firstInputSampleRight;
}
}

Linear Memory

Most Superpowered APIs work on arrays of floating point numbers representing PCM audio. A simple buffer containing audio input for example. But WebAssembly can not access traditional JavaScript Float32Arrays directly and efficiently.

In the low-level memory model of WebAssembly, memory is represented as a contiguous range of untyped bytes called Linear Memory, which is a standard ArrayBuffer.

Memory can be "allocated" in the Linear Memory, returning with a pointer to the allocated region, which can be used to represent an array of data, such as an array of floating point numbers. This pointer (aka address) is just a simple integer Number, the byte index inside the Linear Memory. For example, 0 represents the first byte in the Linear Memory, however Superpowered occupies this part and 0 means "NULL".

The following example demonstrates how to allocate a region in the Linear Memory and how to create a Float32Array "view" of this region with standard WebAssembly JavaScript:

...
let length = 128; // We want the buffer to store 128 floating point numbers.
let pointer = Superpowered.malloc(length * 4); // A floating point number is 4 bytes, therefore we allocate length * 4 bytes of memory.
// You can use "pointer" to pass audio to most Superpowered APIs.
// Maybe we want to directly manipulate this data from JavaScript as well. Let's create a Float32Array view of this region.
let arrayView = new Float32Array(
Superpowered.linearMemory, // Standard WebAssembly Module reference to the Linear Memory.
pointer, // The address of the allocated region.
length // The length of the region.
);
// Now this is possible:
arrayView[0] = 0.5;
// Deallocate the region when we don't need it anymore.
Superpowered.free(pointer);
...

SuperpoweredGlue offers some special typed buffer APIs to make this allocation process a little bit easier:

...
// Total memory consumption in this example: 256 * 4 = 1024 bytes.
let someBuffer = new Superpowered.Float32Buffer(256);
someBuffer.pointer; // Getting the linear memory index (pointer).
someBuffer.length; // Getting the length of the buffer (256).
someBuffer.array; // A Float32Array view of this buffer (standard TypedArray).
someBuffer.array[0] = 0.5; // Accessing the buffer as a Float32Array.
someBuffer.free(); // Deallocate the buffer.
...

Uint8Buffer

Methods
  • constructorMETHOD
    Creates a Superpowered.Uint8Buffer instance.
    Parameters
    NameTypeDescription
    lengthNumberLength of buffer array.
    Returns
    TypeDescription
    Superpowered.Uint8Buffer
  • freeMETHOD
    Deallocate the buffer.
    Parameters
    None
    Returns
    None
Properties
arrayPROPERTY
A Uint8Array view of this buffer (standard TypedArray).
TypeMinMaxDefault
Uint8Array
lengthPROPERTY
The length of the buffer.
TypeMinMaxDefault
Number
pointerPROPERTY
Index in the Linear Memory (pointer).
TypeMinMaxDefault
Number

Int8Buffer

Methods
  • constructorMETHOD
    Creates a Superpowered.Int8Buffer instance.
    Parameters
    NameTypeDescription
    lengthNumberLength of buffer array.
    Returns
    TypeDescription
    Superpowered.Int8Buffer
  • freeMETHOD
    Deallocate the buffer.
    Parameters
    None
    Returns
    None
Properties
arrayPROPERTY
A Int8Array view of this buffer (standard TypedArray).
TypeMinMaxDefault
Int8Array
lengthPROPERTY
The length of the buffer.
TypeMinMaxDefault
Number
pointerPROPERTY
Index in the Linear Memory (pointer).
TypeMinMaxDefault
Number

Uint16Buffer

Methods
  • constructorMETHOD
    Creates a Superpowered.Uint16Buffer instance.
    Parameters
    NameTypeDescription
    lengthNumberLength of buffer array.
    Returns
    TypeDescription
    Superpowered.Uint16Buffer
  • freeMETHOD
    Deallocate the buffer.
    Parameters
    None
    Returns
    None
Properties
arrayPROPERTY
A Uint16Array view of this buffer (standard TypedArray).
TypeMinMaxDefault
Uint16Array
lengthPROPERTY
The length of the buffer.
TypeMinMaxDefault
Number
pointerPROPERTY
Index in the Linear Memory (pointer).
TypeMinMaxDefault
Number

Int16Buffer

Methods
  • constructorMETHOD
    Creates a Superpowered.Int16Buffer instance.
    Parameters
    NameTypeDescription
    lengthNumberLength of buffer array.
    Returns
    TypeDescription
    Superpowered.Int16Buffer
  • freeMETHOD
    Deallocate the buffer.
    Parameters
    None
    Returns
    None
Properties
arrayPROPERTY
A Int16Array view of this buffer (standard TypedArray).
TypeMinMaxDefault
Int16Array
lengthPROPERTY
The length of the buffer.
TypeMinMaxDefault
Number
pointerPROPERTY
Index in the Linear Memory (pointer).
TypeMinMaxDefault
Number

Uint32Buffer

Methods
  • constructorMETHOD
    Creates a Superpowered.Uint32Buffer instance.
    Parameters
    NameTypeDescription
    lengthNumberLength of buffer array.
    Returns
    TypeDescription
    Superpowered.Uint32Buffer
  • freeMETHOD
    Deallocate the buffer.
    Parameters
    None
    Returns
    None
Properties
arrayPROPERTY
A Uint32Array view of this buffer (standard TypedArray).
TypeMinMaxDefault
Uint32Array
lengthPROPERTY
The length of the buffer.
TypeMinMaxDefault
Number
pointerPROPERTY
Index in the Linear Memory (pointer).
TypeMinMaxDefault
Number

Int32Buffer

Methods
  • constructorMETHOD
    Creates a Superpowered.Int32Buffer instance.
    Parameters
    NameTypeDescription
    lengthNumberLength of buffer array.
    Returns
    TypeDescription
    Superpowered.Int32Buffer
  • freeMETHOD
    Deallocate the buffer.
    Parameters
    None
    Returns
    None
Properties
arrayPROPERTY
A Int32Array view of this buffer (standard TypedArray).
TypeMinMaxDefault
Int32Array
lengthPROPERTY
The length of the buffer.
TypeMinMaxDefault
Number
pointerPROPERTY
Index in the Linear Memory (pointer).
TypeMinMaxDefault
Number

BigUint64Buffer

Methods
  • constructorMETHOD
    Creates a Superpowered.BigUint64Buffer instance.
    Parameters
    NameTypeDescription
    lengthNumberLength of buffer array.
    Returns
    TypeDescription
    Superpowered.BigUint64Buffer
  • freeMETHOD
    Deallocate the buffer.
    Parameters
    None
    Returns
    None
Properties
arrayPROPERTY
A BigUInt64Array view of this buffer (standard TypedArray).
TypeMinMaxDefault
BigUInt64Array
lengthPROPERTY
The length of the buffer.
TypeMinMaxDefault
Number
pointerPROPERTY
Index in the Linear Memory (pointer).
TypeMinMaxDefault
Number

BigInt64Buffer

Methods
  • constructorMETHOD
    Creates a Superpowered.BigInt64Buffer instance.
    Parameters
    NameTypeDescription
    lengthNumberLength of buffer array.
    Returns
    TypeDescription
    Superpowered.BigInt64Buffer
  • freeMETHOD
    Deallocate the buffer.
    Parameters
    None
    Returns
    None
Properties
arrayPROPERTY
A BigInt64Array view of this buffer (standard TypedArray).
TypeMinMaxDefault
BigInt64Array
lengthPROPERTY
The length of the buffer.
TypeMinMaxDefault
Number
pointerPROPERTY
Index in the Linear Memory (pointer).
TypeMinMaxDefault
Number

Float32Buffer

Methods
  • constructorMETHOD
    Creates a Superpowered.Float32Buffer instance.
    Parameters
    NameTypeDescription
    lengthNumberLength of buffer array.
    Returns
    TypeDescription
    Superpowered.Float32Buffer
  • freeMETHOD
    Deallocate the buffer.
    Parameters
    None
    Returns
    None
Properties
arrayPROPERTY
A Float32Array view of this buffer (standard TypedArray).
TypeMinMaxDefault
Float32Array
lengthPROPERTY
The length of the buffer.
TypeMinMaxDefault
Number
pointerPROPERTY
Index in the Linear Memory (pointer).
TypeMinMaxDefault
Number

Float64Buffer

Methods
  • constructorMETHOD
    Creates a Superpowered.Float64Buffer instance.
    Parameters
    NameTypeDescription
    lengthNumberLength of buffer array.
    Returns
    TypeDescription
    Superpowered.Float64Buffer
  • freeMETHOD
    Deallocate the buffer.
    Parameters
    None
    Returns
    None
Properties
arrayPROPERTY
A Float64Array view of this buffer (standard TypedArray).
TypeMinMaxDefault
Float64Array
lengthPROPERTY
The length of the buffer.
TypeMinMaxDefault
Number
pointerPROPERTY
Index in the Linear Memory (pointer).
TypeMinMaxDefault
Number

Memory utilities

The memoryCopy and memorySet functions are also available for quick memory operations:

// Allocate two buffers, each with four 32-bit integer numbers (16 bytes).
let buf1 = new Superpowered.Int32Buffer(4);
let buf2 = new Superpowered.Int32Buffer(4);
// buf1 to [ 0, 1, 2, 3 ], buf2 contains memory garbage
buf1.array[0] = 0;
buf1.array[1] = 1;
buf1.array[2] = 2;
buf1.array[3] = 3;
// Copy in Linear Memory. Similar to memcpy in C.
Superpowered.memoryCopy(
buf2.pointer, // Output pointer.
buf1.pointer, // Input pointer.
16 // Number of bytes to copy.
);
// buf2 is now [ 0, 1, 2, 3 ]
// Set data in Linear Memory. Similar to memset in C.
Superpowered.memorySet(
buf1.pointer, // Pointer to data.
0, // Set this value to each byte. Should be between 0..255.
16 // Number of bytes to set.
);
// buf1 is now [ 0, 0, 0, 0 ]
  • memoryCopy

    METHOD
    Copy in Linear Memory. Similar to memcpy in C.
    Parameters
    NameTypeDescription
    outputNumberOutput pointer.
    inputNumberInput pointer.
    bytesNumberNumber of bytes to copy.
    Returns
    None
  • memorySet

    METHOD
    Set data in Linear Memory. Similar to memset in C.
    Parameters
    NameTypeDescription
    dataNumberPointer to data.
    valueNumberSet each byte to this value, should be between 0 - 255.
    bytesNumberNumber of bytes to set.
    Returns
    None

Remember you can find a working example of getting Superpowered up and running with WebAudio here:


C++

is not supported here.

v1.0.6