A
A
alekssamos2019-09-21 12:51:36
JavaScript
alekssamos, 2019-09-21 12:51:36

Get active device ID?

There is such a code. The phone has two cameras and the front one is active by default. And in select the back one is selected. And in order to switch, I need to select the front, although it is already active, and then back again.
How to do this kind of type checking

if (deviceInfo.deviceId == activeDeviceId)
    option.selected = true;

'use strict';
var videoElement = document.querySelector('video');
var videoSelect = document.querySelector('select#videoSource');
videoSelect.onchange = getStream;

getStream().then(getDevices).then(gotDevices);

function getDevices() {
  // AFAICT in Safari this only gets default devices until gUM is called :/
  return navigator.mediaDevices.enumerateDevices();
}

function gotDevices(deviceInfos) {
  window.deviceInfos = deviceInfos; // make available to console
  console.log('Available input and output devices:', deviceInfos);
  for (const deviceInfo of deviceInfos) {
    const option = document.createElement('option');
    option.value = deviceInfo.deviceId;
    if (deviceInfo.kind === 'audioinput') {
      /* option.text = deviceInfo.label || `Microphone ${audioSelect.length + 1}`; */
      /* audioSelect.appendChild(option); */
    } else if (deviceInfo.kind === 'videoinput') {
      option.text = deviceInfo.label || `Camera ${videoSelect.length + 1}`;
      videoSelect.appendChild(option);
    }
  }
  videoSelect.disabled=videoSelect.length<=1;
}

function getStream() {
  if (window.stream) {
    window.stream.getTracks().forEach(track => {
      track.stop();
    });
  }
  const videoSource = videoSelect.value;
  const constraints = {
    video: {deviceId: videoSource ? {exact: videoSource} : undefined}
  };
  return navigator.mediaDevices.getUserMedia(constraints).
    then(gotStream).catch(handleError);
}

function gotStream(stream) {
  window.stream = stream; // make stream available to console
  videoSelect.selectedIndex = [...videoSelect.options].
    findIndex(option => option.text === stream.getVideoTracks()[0].label);
  if ('srcObject' in videoElement) {
    videoElement.srcObject = stream;
  } else {
    videoElement.src = URL.createObjectURL(stream);
  }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question