I’m trying to get video from client’s Webcam. I wrote the code, and no errors occurred. However, when I try to get video, nothing shows up (in Google Chrome) or just a single frame of the video is displayed (in Mozilla Firefox). I have tested it out before and it worked completely fine, but now, I don’t know why, it doesn’t work. I searched for it, and found nothing about it. Any help is really appreciated. Thanks
Here’s my code:
JavaScript
x
49
49
1
<!DOCTYPE html>
2
<html lang="en">
3
<head>
4
<meta charset="UTF-8">
5
<meta http-equiv="X-UA-Compatible" content="IE=edge">
6
<meta name="viewport" content="width=device-width, initial-scale=1.0">
7
<title>Document</title>
8
<style>
9
html, body {
10
height: 100%;
11
}
12
body {
13
margin: 0;
14
}
15
video {
16
width: 100%;
17
height: 100%;
18
position: absolute;
19
left: 0;
20
top: 0;
21
z-index: -1;
22
}
23
</style>
24
</head>
25
<body>
26
<button id="shareBtn">Share Video</button>
27
28
<script>
29
async function startCapture(displayMediaOptions) {
30
let stream = null;
31
32
try {
33
stream = await navigator.mediaDevices.getUserMedia(displayMediaOptions);
34
video = document.createElement("video");
35
video.srcObject = stream;
36
document.body.appendChild(video);
37
} catch(err) {
38
console.error(err);
39
}
40
}
41
document.getElementById("shareBtn").addEventListener("click", () => {
42
43
startCapture({ video:true });
44
45
});
46
</script>
47
</body>
48
</html>
49
Advertisement
Answer
Your code is working, but video is paused. Add 1 line to your code:
JavaScript
1
21
21
1
<script>
2
async function startCapture(displayMediaOptions) {
3
let stream = null;
4
5
try {
6
stream = await navigator.mediaDevices.getUserMedia(displayMediaOptions);
7
video = document.createElement("video");
8
video.srcObject = stream;
9
video.setAttribute('autoplay', true); /* THIS */
10
document.body.appendChild(video);
11
} catch(err) {
12
console.error(err);
13
}
14
}
15
document.getElementById("shareBtn").addEventListener("click", () => {
16
17
startCapture({ video:true });
18
19
});
20
</script>
21