javascriptweb-audio-apiaudiocontextsample-rate

How to get the sample rate of a microphone/input device using Javascript?


When you create a new AudioContext it sets the sample rate to the default output device. This is expected default behavior. Does anyone know if there is there any way to get the sample rate of the input device in Javascript?

We can see in the docs for AudioContext it says this about sampleRate

The value will typically be between 8,000 Hz and 96,000 Hz; the default will vary depending on the output device, but the sample rate 44,100 Hz is the most common. If the sampleRate property is not included in the options, or the options are not specified when creating the audio context, the new context's output device's preferred sample rate is used by default.

Example of how I'm using it:

const stream = await navigator.mediaDevices.getUserMedia({audio: true, video: false});
const context = new AudioContext();
context.sampleRate // This is the default output device's sample rate. I need the default input sampleRate

I've been scouring the docs and the internet for a way to do this but have not found anything useful. Appreciate any help.


Solution

  • You can get the sampleRate of the audio track within the stream like this:

    const sampleRate = stream.getAudioTracks()[0].getSettings().sampleRate;
    

    You can then use that to create the AudioContext.

    const context = new AudioContext({ sampleRate });