How to achieve vertical WebRTC streaming on a mobile device

305 views
Skip to first unread message

Juancar

unread,
Jul 24, 2024, 5:19:23 AM7/24/24
to discuss-webrtc
I need a WebRTC streaming in portrait mode. I've tested with this simple code. In desktop it works, but in mobile device it does not.

I’ve seen other solutions where the video component is rotated 90 degrees with CSS, but that approach has a problem. When the user “moves upwards” with the mobile device, the video moves to the side, making it very difficult to aim at an object. This results in a poor user experience when using the camera.

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Camare Vertical</title>
    <style>
        body, html {
            margin: 0;
            padding: 0;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            background-color: #000;
        }
        #videoContainer {
            width: 95vw;
            height: 95vh;
            max-width: 95vw;
            max-height: 95vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        #videoElement {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }
    </style>
</head>
<body>
    <div id="videoContainer">
        <video id="videoElement" autoplay playsinline></video>
    </div>

    <script>
        const videoElement = document.getElementById('videoElement');

        async function initCamera() {
            try {
                const stream = await navigator.mediaDevices.getUserMedia({
                    video: {
                        facingMode: 'environment',
                        width: { ideal: 1080 },
                        height: { ideal: 1920 },
                        aspectRatio: { ideal: 9/16 }
                    }
                });

                videoElement.srcObject = stream;

                videoElement.onloadedmetadata = () => {
                    const { videoWidth, videoHeight } = videoElement;
                    console.log(`${videoWidth}x${videoHeight}`);
                };
            } catch (error) {
                console.error('Error:', error);
            }
        }

        window.addEventListener('load', initCamera);
    </script>
</body>
</html>

Reply all
Reply to author
Forward
0 new messages