Search code examples
javascriptwebrtc

How to set bitrate with webRTC in js?


Here is the code

var constraints = {
       video: {
          width: {exact: 320},
          height: {exact: 240},
          bitRate: {
            max: 400,
            min: 400,
          },
          frameRate: {
            min: 15,
            max: 15
          }
        },
      }

window.navigator.mediaDevices.getUserMedia(constraints);

It seems width, height, frameRate all work fine, but bitRate not works.

Can js set bitRate in webRTC, or any other way reduce record video size?

I test find that video size record in iPhone safari too big to wait uploading.


Solution

  • The MediaStream that you get when calling getUserMedia() doesn't know anything about bitrates. It's always dealing with the raw media.

    But you can control the bitrate when sending the MediaStream via a PeerConnection. It can be either done by manually modifying the SDP or by updating the parameters of the corresponding sender.

    const senders = peerConnection.getSenders();
    
    // Let's say you want to modify the first.
    const parameters = senders[0].getParameters();
    
    parameters.encodings[0].maxBitrate = YOUR_MAX_BITRATE;
    
    sender.setParameters(parameters);
    

    You can also set the bitrate when recording the MediaStream with a MediaRecorder.

    new MediaRecorder(
        mediaStream,
        {
            // You can either set the values for audio and video separately ...
            audioBitsPerSecond: YOUR_MAX_BITRATE_FOR_AUDIO,
            videoBitsPerSecond: YOUR_MAX_BITRATE_FOR_VIDEO,
            // ... or you define one value for audio and video.
            bitsPerSecond: YOUR_MAX_BITRATE_FOR_AUDIO_AND_VIDEO
        }
    );