← View all posts
September 1, 2017

channelCount constraint for microphone input

Contributed by achronopoulos@mozilla.com,

The channelCount microphone constraint is now available in Firefox Beta. If you want to control the number of channels of audio input from a getUserMedia call, this post is for you.

Previously, just one channel (mono sound) was possible. But as of Firefox 55, two channels (stereo sound) is the default. Now, the channelCount constraint allows you to control the number of channels that your microphone will deliver.

The constraint can be specified in the initial getUserMedia() request, as well as changed later using the track.applyConstraints() method. If set, Firefox will try to obtain media closest to the requested value according to the capabilities of the hardware.

A channel count equal to 1 corresponds to mono audio, 2 to stereo, and so forth.

Working example

The following example assumes that a stereo capable input device is available – which is common these days – and that you’re using Firefox 56 or newer. Please note that, due to bug 1392837, some microphones (particularly on new mac books) may not work correctly if they are configured to output 4 channels at the OS level.

Warning: Put on headphones or lower volume, or this may feedback

In the example above you can use one of the buttons, on the top, to make the initial getUserMedia request. You can chose either default (channel count not specified), mono, stereo or 4 channels. With web audio we split the audio into individual channels to get a visual representation per channel. Pressing mono button you see only one visualizer, corresponding to a single channel. On the other hand, pressing stereo (or default using a stereo capable device) button you see two visualizers. Each one corresponds to a different channel. Now, if you request 4 channels on a stereo device the result will be stereo. This is because 2 channels is the closest to the requested value. Finally, you can demand 4 channels by using the exact keyword. In this case, the request fails and the result is an OverConstraint error.

On the active stream, you can switch between mono and stereo, on the fly, using the radio buttons on the bottom. This is done using applyConstraints and the changes are again reflected visually.

Enjoy …