getBuffer
Get the decoded AudioBuffer of a sound. Use it to draw a waveform, read the sample rate, or feed the audio into your own Web Audio nodes.
getBuffer(id: string): AudioBuffer | undefined;
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
id | string | required | ID of a loaded sound. |
Returns
AudioBuffer | undefined: the decoded audio, or undefined when the id is not loaded.
Example
import { SoundHub } from 'soundhub';
const soundHub = new SoundHub();
await soundHub.loadSound('music', '/audio/theme.mp3');
const buffer = soundHub.getBuffer('music');
if (buffer) {
console.log(`${buffer.duration}s, ${buffer.numberOfChannels} channels, ${buffer.sampleRate} Hz`);
const samples = buffer.getChannelData(0); // Float32Array for a waveform
}
Good to know
- For an id that is not loaded, the error is logged, stored for
getLastErrorand dispatched as anerrorevent. CheckhasSoundfirst to avoid that. - Streams have no buffer, so a stream id also returns
undefinedand logs the error. - A sprite sound such as
ui_jumphas its own buffer holding only that range. - The buffer is the one the hub plays from, not a copy. Writing into its channel data changes what later plays.
See also
getSound: the whole sound object.getDuration: just the length in seconds.getSource: the source node playing the buffer.addBuffer: the other way round, add a buffer you have as a sound.