JSFiddle - React, Tailwind, and code Playground

by morphcast

HTML

<!DOCTYPE html>
<html>
<head>
    <title>MorphCast Dynamic Camera Selector</title>
    <script src="https://ai-sdk.morphcast.com/v1.16/ai-sdk.js"></script>
</head>
<body>
    <h1>Camera Selector</h1>
    <video id="morphcastVideo" autoplay playsinline muted style="width: 640px; height: 480px; border: 1px solid black;"></video>
    <br>
    <label for="cameraSelect">Select Camera:</label>
    <select id="cameraSelect"></select>

    <script>
        const videoElement = document.getElementById('morphcastVideo');
        const cameraSelect = document.getElementById('cameraSelect');
        let currentCameraSource = null;
        let morphcastCY = null; // Your CY instance after loader().load()

        async function populateCameraList() {
            try {
                // Request permission first (important for some browsers before enumerateDevices)
                await navigator.mediaDevices.getUserMedia({ video: true, audio: false });

                const devices = await navigator.mediaDevices.enumerateDevices();
                const videoDevices = devices.filter(device => device.kind === 'videoinput');

                cameraSelect.innerHTML = ''; // Clear existing options
                videoDevices.forEach((device, index) => {
                    const option = document.createElement('option');
                    option.value = device.deviceId;
                    option.text = device.label || `Camera ${index + 1}`;
                    cameraSelect.appendChild(option);
                });

                if (videoDevices.length > 0) {
                    // Automatically start with the first camera or a saved preference
                    await switchCamera(videoDevices[0].deviceId);
                } else {
                    console.error("No video input devices found.");
                    alert("No video input devices found. Please ensure you have a camera connected and permissions are granted.");
    ...