Skip to main content

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​

ParameterTypeDefaultDescription
idstringrequiredID 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 getLastError and dispatched as an error event. Check hasSound first to avoid that.
  • Streams have no buffer, so a stream id also returns undefined and logs the error.
  • A sprite sound such as ui_jump has 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.