반응형

Video 출력

User의 기기에 있는 디바이스에 접근하기 위해 navigator.mediaDevices.getUserMedia를 사용해야한다.

유저의 미디어를 string으로 전해 줄 것이다. 

이건 async function으로 해야한다.

//constraints는 기본적으로 우리가 무엇을 더고 싶은지 작성해야한다.
async function getMedia(constraints) {
  try {
    stream = await navigator.mediaDevices.getUserMedia({
    //constraints
    audio:true,
    video:true,
    });
    myFace.srcObject = stream;
  } catch (e) {
    console.log(e);
  }
}

 

Video 동작 

이렇게 stream을 가져오게 되면 우리에게 track이라는 것을 제공해줄것이다. 우리는 해당 Track에 접근할 수 있다.

function handleMute() {
  stream.getAudioTracks().forEach((each) => (each.enabled = !each.enabled));
  if (!muteBtn) {
    muteBtn = true;
    micBtn.innerText = "MIC MUTE";
  } else {
    muteBtn = false;
    micBtn.innerText = "MIC UNMUTE";
  }
}
function handleVideoOnOff() {
  stream.getVideoTracks().forEach((each) => (each.enabled = !each.enabled));
  if (!videoOnOff) {
    videoOnOff = true;
    videoBtn.innerText = "VIDEO OFF";
  } else {
    videoOnOff = false;
    videoBtn.innerText = "VIDEO ON";
  }
}

 

또한 설치되어 있는 카메라들에게도 접근이 가능하다.

enumerateDevices는 모든 장치와 미디어장치를 알려준다.

장치를 가져오고 select element를 통한 이벤트를 주어서 select의 value가 변할 때  장치의 화면이 바뀌게 코드를 수정한다.

이 때 getMedia에 인자를 주어 코드를 수정한다.

async function findDevices() {
  try {
    const myAllDevice = await navigator.mediaDevices.enumerateDevices();
    const myCamDevice = myAllDevice.filter(
      (device) => device.kind === "videoinput"
    );
    const currentCam = stream.getVideoTracks()[0];
    camSelect.innerHTML = "";
    myCamDevice.forEach((each) => {
      const option = document.createElement("option");
      option.value = each.deviceId;
      option.innerText = each.label;
      if (currentCam.label === each.label) {
        option.selected = true;
      }
      camSelect.appendChild(option);
    });
  } catch (e) {
    console.log(e);
  }
}

async function handleCamChange() {
  await getMedia(camSelect.value);
}

async function getMedia(constraints) {
  const basicConstraints = {
    audio: true,
    video: {facingMode: "user"},
  };
  const mutateConstraints = {
    audio: true,
    video: {
      deviceId: constraints,
    },
  };
  try {
    stream = await navigator.mediaDevices.getUserMedia(
      !constraints ? basicConstraints : mutateConstraints
    );

    if (!constraints) {
      await findDevices();
    }
    myFace.srcObject = stream;
  } catch (e) {
    console.log(e);
  }
}

 

 

728x90

'SocketIO & WebRTC > WebRTC' 카테고리의 다른 글

WebRTC (ICE Candidate / Senders / Stun)__003  (0) 2023.11.24
WebRTC (SocketIO / Offer / Answer )__002  (0) 2023.11.23

+ Recent posts