LePhenix47 / Lahouiti_Younes_P13_21062024

This repo contains the code for the a Proof of Concept (PoC) for the "Your car your way" app for the support page using WebSockets for the chat and WebRTC for the videoconference
MIT License
1 stars 0 forks source link

Local media web API methods #4

Closed LePhenix47 closed 2 months ago

LePhenix47 commented 3 months ago

To get the webcam or microphone:

// To access the user's webcam and microphone
try {
    const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true })
    const videoElement = document.querySelector('#localVideo');
    videoElement.srcObject = stream;
} catch(error) {
    console.error('Error accessing media devices.', error);
}

On mobile (front & back facing camera):

// To access the front-facing camera on mobile
const hasFrontCameraEnabled = true

try {
    const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: hasFrontCameraEnabled ? 'user' :'environment' }, audio: true });
    const videoElement = document.querySelector('#localVideo');
    videoElement.srcObject = stream;

} catch(error) {
    console.error('Error accessing media devices.', error);
}

To get the screen cast:

// To access the user's screen for screen sharing
try {
    const screenStream = await navigator.mediaDevices.getDisplayMedia({ video: true })
    const videoElement = document.querySelector('#screenVideo');
    videoElement.srcObject = screenStream;

} catch(error) {
    console.error('Error accessing display media.', error);
}

To get the local devices for the webcam and microphone:

// To list available media devices (webcams and microphones)
try {
    const devices = await navigator.mediaDevices.enumerateDevices();

    devices.forEach((device) => {
        if (device.kind === 'videoinput') {
            console.log('Webcam: ', device.label || 'Camera ' + device.deviceId);
        } else if (device.kind === 'audioinput') {
            console.log('Microphone: ', device.label || 'Microphone ' + device.deviceId);
        }
    });
} catch(error) {
    console.error('Error listing devices.', error);
}
LePhenix47 commented 3 months ago

State management

If you have a WebRTC session starting, you're on mobile and want to switch cameras

// Assuming you already have a reference to the RTCPeerConnection and the existing track
const sender = pc.getSenders().find(s => s.track.kind === 'video');

sender?.replaceTrack(newVideoTrack);