Search code examples
javascriptaudio-recordingmicrophonemediarecorder

How to specify bit depth and sample rate when recording microphone using mediaRecorder in javascript?


In general, a standard CD's duration is 74 min, sample rate is 44.1KHZ, left and right two-channel (stereo). Its capacity can be calculated using the following formula:

(44100*16*2)/8*(74*60)=783216000bytes

Does 16 mean the bit depth?

Below is the code snippet that I use to do the recording.

const options = {
    mimeType: 'audio/webm;codecs=pcm',
    audioBitsPerSecond: 128
};
const recordedChunks = []
const mediaRecorder = new MediaRecorder(stream, options)
mediaRecorder.addEventListener('dataavailable', function (e) {
    if (e.data.size > 0) {
        recordedChunks.push(e.data)
    }
})
mediaRecorder.addEventListener('stop', function () {
    fileReader.readAsDataURL(new Blob(recordedChunks))
})
mediaRecorder.start()

After searching the documentation, I didn't find the bit depth, channel and sample rate option. Any ideas?


Solution

  • You can specify the sample rate, channel count, and bit depth by modifying a MediaTrackConstraints object, then applying it to a MediaStreamTrack using MediaStreamTrack.applyConstraint(constraints). The MediaStreamTrack should be accessible through the MediaStream going into your MediaRecorder.

    (The 16 in your equation does refer to the bit-depth)

    (44100 samples * 16 bits per sample * 2 channels of audio) / 8 bits per byte * (74 minutes * 60 seconds per minute) = 783216000 bytes