Home > Mobile >  Displaying video using WebRTC in javascript
Displaying video using WebRTC in javascript

Time:11-21

I am currently learning how to utilize WebRTC in javascript.
Here are the codes I wrote:

main.html

<!DOCTYPE html>
<header>
  <title>video and audio</title>
  <style>
    html {
      height: 100%;
    }
    body {
      min-height: 100%;
      height: 100%;
      margin: 0;
    }

    #video {
      height: 50%;
      width: 50%;
      border: 1px solid black;
    }
    #audio {
      height: 50%;
      width: 50%;
      border: 1px solid black;
    }
  </style>
</header>
<body>
  <div id="video"></div>
  <div id="audio"></div>
</body>
<script src="WebRTC.js" type="text/javascript"></script>
</html>

WebRTC.js

const constraints = {audio: true, video: {width: 1280, height: 70}}

navigator.mediaDevices.getUserMedia(constraints)
.then (
  (mediaStream) => {
    console.log('success')
    const video = document.querySelector('#video');
    video.srcObject = mediaStream;
    video.onloadedmetadata = () => {video.play();}
  })
.catch (
  console.log('unsuccessful')
)

When I open it, it asks me permission to access my camera, and the console returns "successful." So I think that the code is working fine However, the video is not displayed on the <div id="video">. I googled the solution, but I have come up with nothing yet. I would be appreciated it if you could help me find what I am missing here. Thank you very much.

CodePudding user response:

In order to be able to play video on your page, you need to use the <video /> tag instead of plain <div />. So you just need to change

<div id="video"></div>
<div id="audio"></div>

with

<video autoplay="true"></video>

Your final code will be like this:

const constraints = {
  audio: true,
  video: {
    width: 1280,
    height: 70
  }
}

navigator.mediaDevices.getUserMedia(constraints)
  .then(
    (mediaStream) => {
      console.log('success')
      const video = document.querySelector('video');
      video.srcObject = mediaStream;
      video.onloadedmetadata = () => {
        video.play();
      }
    })
  .catch(
    console.log('unsuccessful')
  )
html {
  height: 100%;
}

body {
  min-height: 100%;
  height: 100%;
  margin: 0;
}

video {
  height: 50%;
  width: 50%;
  border: 1px solid black;
}
<video autoplay="true"></video>

Codepen: https://codepen.io/SMAKSS/pen/RwJxjpb

CodePudding user response:

It's not working because you are using a div tag instead of a video tag.

Just use the video tag below.

<video id="video"></video>
  • Related