Search code examples
web-audio-apiaudio-processingaudiocontext

How to render in a specific bit depth?


How can OfflineAudioContext.startRendering() output an AudioBuffer that contains the bit depth of my choice (16 bits or 24 bits)? I know that I can set the sample rate of the output easily with AudioContext.sampleRate, but how do I set the bit depth?

My understanding of audio processing is pretty limited, so perhaps it's not as easy as I think it is.

Edit #1:

Actually, AudioContext.sampleRate is readonly, so if you have an idea on how to set the sample rate of the output, that would be great too.

Edit #2:

I guess the sample rate is inserted after the number of channels in the encoded WAV (in the DataView)


Solution

  • You can't do this directly because WebAudio only works with floating-point values. You'll have to do this yourself. Basically take the output from the offline context and multiply every sample by 32768 (16-bit) or 8388608 (24-bit) and round to an integer. This assumes that the output from the context lies within the range of -1 to 1. If not, you'll have to do additional scaling. And finally, you might want to divide the final result by 32768 (8388608) to get floating-point numbers back. That depends on what the final application is.

    For Edit #1, the answer is that when you construct the OfflineAudioContext, you have to specify the sample rate. Set that to the rate you want. Not sure what AudioContext.sampleRate has to do with this.

    For Edit #2, there's not enough information to answer since you don't say what DataView is.