Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to maintain a landscape aspect ratio with getUserMedia on mobile devices?

I'm using getUserMedia with the following constraints:

var constraints = {
    audio: true,
    video: {
        width: 960,
        height: 540,
    }
};

navigator.mediaDevices.getUserMedia(constraints).then(...);

This works when using desktops or when using mobile devices while they are in landscape mode. However, when rotating the mobile device to portrait mode, the video object loses the aspect ratio:

When the device is held as Landscape:

enter image description here

When the device is held as Portrait:

enter image description here

This happens both on iOS and Android devices, on Chorme, Safari and Samsung browser.

I tried playing around with the constraints aspectRatio, min, ideal as suggested by the MDN docs, but it seems these constraints are of no effect at all.

Is there any way to always maintain the aspect ratio as 1.777 even if the mobile device is rotated as portrait mode?

like image 940
Koby Douek Avatar asked Nov 07 '22 04:11

Koby Douek


1 Answers

I found out that you can use reversed aspectRatio when in Portrait mode.

I use this constraints in Landscape mode:

mediaConstraints: MediaStreamConstraints = {
  video: {
    aspectRatio: 16/9
  }
};

and this constraints in Portrait mode:

mediaConstraints: MediaStreamConstraints = {
  video: {
    aspectRatio: 9/16
  }
};

The caveat of this solution is you have to detect orientation change and call again getUserMedia(), losing your stream.

Also if you are recording the stream, you should prevent screen rotation with ScreenOrientation.lock() (not working in Safari) so user is not able to reset stream by rotating device while recording.

like image 72
Dragonduck Avatar answered Nov 14 '22 13:11

Dragonduck