addBuffer
Added in 6.5.0
Add audio that is already in memory as a sound. The buffer can come from your own synthesis, a recording or a file you decoded yourself. From then on it plays, fades, pans and reports like a sound from loadSound.
addBuffer(id: string, buffer: AudioBuffer): void;
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
id | string | required | ID for the sound. An id that is already in use is replaced. |
buffer | AudioBuffer | required | The audio. Create it on the hub's own context, see below. |
Returns
Nothing. The sound is ready as soon as the call returns, there is nothing to await.
Example
A short beep, rendered in code:
import { SoundHub } from 'soundhub';
const soundHub = new SoundHub();
const context = soundHub.getContext();
const seconds = 0.15;
const buffer = context.createBuffer(1, Math.ceil(seconds * context.sampleRate), context.sampleRate);
const samples = buffer.getChannelData(0);
for (let i = 0; i < samples.length; i++) {
const fade = 1 - i / samples.length;
samples[i] = Math.sin((2 * Math.PI * 880 * i) / context.sampleRate) * fade * 0.5;
}
soundHub.addBuffer('beep', buffer);
soundHub.play('beep');
A recording from the microphone
const blob = await recordClip(); // your MediaRecorder code
const buffer = await soundHub.getContext().decodeAudioData(await blob.arrayBuffer());
soundHub.addBuffer('take-1', buffer);
soundHub.play('take-1', { playbackRate: 0.8 });
Try it
A sound from a buffer
IdlePick a pitch and a length, then render the beep and play it. Nothing is fetched.
Iddemo-beep
getDuration-
After addBuffer the beep is an ordinary sound: it fades, pans and reports on the event bus like a loaded file.
Code
Your clicks show up here as soundhub calls
Good to know
- A
loadedevent is dispatched for the new sound, with its duration, sample rate and channel count. It has no url. getLoadStatereturns'loaded'right after the call.- An id in use by a sound or stream is unloaded first, which dispatches
unloadedfor the old one. - A variation name from
createVariationscannot be used as the id. That throws an error. - Make the buffer with
soundHub.getContext().createBuffer()ordecodeAudioDataon the same context, so the sample rate matches the hub. - The hub plays from your buffer, it does not copy it. Writing into its channel data afterwards changes what plays next.
soundhub/uiuses this method to add its interface sounds.
See also
loadSound: load a sound from a url.getBuffer: the buffer of a loaded sound.- Interface sounds: twelve sounds rendered in the browser.