Skip to main content

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​

ParameterTypeDefaultDescription
idstringrequiredID for the sound. An id that is already in use is replaced.
bufferAudioBufferrequiredThe 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​

Try it

A sound from a buffer

Idle

Pick a pitch and a length, then render the beep and play it. Nothing is fetched.

440 Hz
0.40 s
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 loaded event is dispatched for the new sound, with its duration, sample rate and channel count. It has no url.
  • getLoadState returns 'loaded' right after the call.
  • An id in use by a sound or stream is unloaded first, which dispatches unloaded for the old one.
  • A variation name from createVariations cannot be used as the id. That throws an error.
  • Make the buffer with soundHub.getContext().createBuffer() or decodeAudioData on 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/ui uses this method to add its interface sounds.

See also​