Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to react to changes in the dimension/size of a video track in a `MediaStream`?

In my web app I obtain a MediaStream either via getUserMedia or getDisplayMedia. In certain situations, the video track of that stream can change its size. For example, if getDisplayMedia tracks a specific window, that window can change size. Or on a mobile device, when switching from landscape into portrait mode, the camera image will be rotated by 90° (i.e. width and height get swapped).

I know how to get the dimensions of the MediaStream (as described here). I now want to get notified whenever the dimensions change. A callback/event of some sorts.

I already tried MediaStream.onaddtrack (guessing that maybe the track is removed and readded with a different size) and I also tried using a MutationObserver on the <video> element I am showing the stream in. None of these worked. I also checked MDN for other events that might help me, but I didn't find any promising ones.

Is there a way to subscribe to changes of a video track's dimension? A function of mine should be called each time the dimensions change. And if it's not possible and I would need to busy poll: is there a smart way how to make the polling a bit less busy?

like image 830
Lukas Kalbertodt Avatar asked Feb 25 '20 17:02

Lukas Kalbertodt


1 Answers

You can subscribe to resize event of your video element

const video = document.getElementById("video");

video.addEventListener("resize", (e) => {
  const { videoWidth, videoHeight } = video;
  // can do smth here
  // for example
  video.style.width = videoWidth;
  video.style.height = videoHeight;

}, false);
like image 62
Firanolfind Avatar answered Sep 23 '22 06:09

Firanolfind