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:
// Create a SuperpoweredGlue instance and fetch the Superpowered WebAssembly from a publicly accessible location on the web. This happens at runtime, not build!
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.
Creates an instance of the SupowereedWebAudio class.
Parameters
Name
Type
Description
samplerate
Number
The initial sample rate in Hz.
Superpowered
Number
An initialised Superpowered instance.
Returns
Type
Description
Superpowered.WebAudioManager
A 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
Name
Type
Description
url
Number
The publicly accessible AudioWorkletProcessor module.
name
Number
The name of the Processor you have registered within your AudioWorkletProcessor script (case-sensitive)
onSuccess
Number
Runs after the audio node is created. Single argument `newNode`, which is a standard AudioNode or a ScriptProcessorNode for use in your WebAudio graph.
onMessageFromAudioScope
Number
Is 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
Name
Type
Description
url
Number
The publicly accessible AudioWorkletProcessor module.
name
Number
The name of the Processor you have registered within your AudioWorkletProcessor script (case-sensitive)
onSuccess
Number
Runs after the audio node is created. Single argument `newNode`, which is a standard AudioNode or a ScriptProcessorNode for use in your WebAudio graph.
onMessageFromAudioScope
Number
Is called whenever `sendMessageToAudioScope` is called from the within the AudioWorkletProcessor. Single argument `message` provided.
Returns
Type
Description
Number
A 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
Name
Type
Description
mediaConstraints
Number
See here for more information about MediaContraints.
onSuccess
Number
Callback on successful audio capture. Single argument `stream` provided.
onError
Number
Callback on unsuccessful audio capture. Single argument `error` provided.
Returns
None
getUserMediaForAudioAsync
METHOD
Asynchronous version of getUserMediaForAudio.
Parameters
Name
Type
Description
mediaConstraints
Number
See here for more information about MediaContraints.
Returns
Type
Description
Number
Returns with a standard MediaStream object or undefined on error.
Code examples
var webaudioManager =newSuperpoweredWebAudio(
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.
// 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.
// 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 =newFloat32Array(
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 =newSuperpowered.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
Name
Type
Description
length
Number
Length of buffer array.
Returns
Type
Description
Superpowered.Uint8Buffer
freeMETHOD
Deallocate the buffer.
Parameters
None
Returns
None
Properties
arrayPROPERTY
A Uint8Array view of this buffer (standard TypedArray).