Chris
Chris

Reputation: 26878

Playing raw audio PCM samples in Web Audio

I have an array of sound samples (16-bit):

[0, 120, 320, 120, 0, -100, -30000, 65, 2, 3, 10, ...]

They range -32768 to 32767. I would like to be able to play the samples using the Web Audio API.

I know that it expects the source buffer to be an ArrayBuffer, but I can't quite figure out how to convert a bunch of samples to an ArrayBuffer to be played with the Web Audio API.

Any tips?

Upvotes: 6

Views: 2185

Answers (1)

cwilso
cwilso

Reputation: 13908

create a new AudioContext, use CreateBuffer to create an AudioBuffer of the right length and number of channels, and then use getChannelData to access the bits - then run through a loop that for each sample sets the bufferData[i] = (original_data[i] / 32768);

Upvotes: 6

Related Questions