Switch between cameras

felix9607 edited this page Nov 15, 2017 · 1 revision

This page explains how to dynamically switch & change selected cameras. That is, it explains how to implement Google+ hangout like switch between cameras behaviour.

First step is to get list of enumerated devices. You can append them in a <select> element as following:

// audioInputDevices  == <select>
// audioOutputDevices == <select>
// videoOutputDevices == <select>

connection.enumerateDevices(function(devices) {
    devices.forEach(appendOption);

    function appendOption(device) {
        var option = document.createElement('option');
        option.innerHTML = device.label || (device.kind + ': ' + device.deviceId);
        option.value = device.deviceId;

        if (device.kind == 'audioinput' || device.kind == 'audio') {
            audioInputDevices.appendChild(option);
        } else if (device.kind == 'audiooutput') {
            audioOutputDevices.appendChild(option);
        } else videoOutputDevices.appendChild(option);
    }
});

Now, assuming that there is a "switch" button:

document.getElementById('btn-switch-cameras').onclick = function() {
    // todo(fix): currently API provides maximum two selections
    connection.selectDevices(audioInputDevices.value);
    connection.selectDevices(videoOutputDevices.value);
    // connection.selectDevices(audioOutputDevices.value);

    // below code switches between cameras
    // removes old streams
    // negotiates new streams
    if (connection.stats.numberOfConnectedUsers <= 0) return; // if session isn't active, simply skip!

    // remove all local video streams
    connection.removeStream({
        video: true,
        local: true
    }, true);

    // add new camera to existing peer connections
    connection.addStream({
        audio: true,
        video: true
    });
};

Now your application is providing Google+ hangout like behaviour for switching different cameras whilst session is on the go!