/
video.js
141 lines (93 loc) · 3.02 KB
/
video.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
var video;
var hidden_ctx;
var showBgImg = false;
var showVideo = false;
document.addEventListener("DOMContentLoaded", function() {
hidden_ctx = createHiddenCanvas("hidden_canvas");
video = document.createElement('video');
document.body.appendChild(video);
video.autoplay = true;
video.loop = true;
video.setAttribute("id", "videoOutput");
video.setAttribute("style", "display:none;");
video.width = 320;
video.height = 240;
// check if browser supports getUserMedia - yes we are looking at you Safari!
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
if (navigator.getUserMedia) {
if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) {
console.log("enumerateDevices() not supported.");
return;
}
// List cameras and microphones.
navigator.mediaDevices.enumerateDevices()
.then(function(devices) {
gotSources(devices);
})
.catch(function(err) {
console.log(err.name + ": " + err.message);
});
}
//CHOOSE WHICH CAMERA TO USE
function setupCamera(cameras){
//console.log(cameras)
//var videoSource = cameras[cameras.length-1].id;
var videoSource = cameras[0].id;
var constraints = {
// audio: {
// optional: [{
// sourceId: audioSource
// }]
// },
video: {
optional: [{
sourceId: videoSource
}]
}
}
navigator.getUserMedia(constraints, successCallback, errorCallback);
}
function successCallback(stream) {
if (video.mozCaptureStream) {
video.mozSrcObject = stream;
} else {
video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
}
video.play();
this.video = video;
}
function errorCallback(error) {
alert('Unable to get webcam stream.');
}
// hacky loop to make sure video is streaming
video.addEventListener('loadeddata', function() {
var attempts = 50;
function checkVideo() {
if (attempts > 0) {
if (video.videoWidth > 0 && video.videoHeight > 0) {
video.available = true;
} else {
// Wait a bit and try again
window.setTimeout(checkVideo, 100);
}
} else {
// Give up after 10 attempts
alert('Unable to play video stream. Is webcam working?');
}
attempts--;
}
checkVideo();
}, false);
function gotSources(devices) {
var cameras = [];
devices.forEach(function(device) {
// console.log(device.kind + ": " + device.label + " id = " + device.deviceId);
if (device.kind === 'videoinput') {
//console.log(device.deviceId);
cameras.push(device);
}
})
setupCamera(cameras);
};
})