forked from alexfromapex/camera-viewer
-
Notifications
You must be signed in to change notification settings - Fork 1
/
view-camera.js
92 lines (79 loc) · 2.3 KB
/
view-camera.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
let cameras = [];
let camId = 0;
let currentStream = null;
document.addEventListener('readystatechange', (event) => {
if(document.readyState === 'complete') {
const video = document.querySelector('video');
function successCallback(stream) {
currentStream = stream;
video.srcObject = stream;
video.play();
if (location.href.includes('&debug')) {
console.log(`stream: ${stream}`);
}
// PATCH: return the enumerate here as a promise..
return navigator.mediaDevices.enumerateDevices();
}
function errorCallback(error) {
window.alert('Error: ', error);
}
navigator.mediaDevices.getUserMedia({audio: false, video: true})
.then(successCallback)
// Patch made by: github user matthewdfleming (https://github.com/matthewdfleming)
// PATCH: so we can then after the prompt, enumerate the devices
.then(media_devices => {
media_devices.forEach(media_device => {
if (location.href.includes('&debug')) {
console.log(media_device);
}
if (media_device.kind === 'videoinput') {
cameras = cameras.concat(media_device.deviceId);
}
})
})
.catch(errorCallback);
if('mediaDevices' in navigator && 'enumerateDevices' in navigator.mediaDevices) {
if(navigator.mediaDevices.enumerateDevices) {
navigator.mediaDevices.enumerateDevices().then(media_devices => {
media_devices.forEach(media_device => {
if(location.href.includes('&debug')) {
console.log(media_device);
}
if(media_device.kind === 'videoinput') {
cameras = cameras.concat(media_device.deviceId);
}
})
})
}
}
video.addEventListener('dblclick',event => {
if(location.href.includes('&debug')) {
console.log('clicked on video');
console.log(cameras);
console.log(camId);
console.log(currentStream);
}
if((camId + 1) < cameras.length) {
camId = camId +1;
} else {
camId = 0;
}
if(cameras.length > 1) {
if(navigator.mediaDevices || navigator.mediaDevices.enumerateDevices) {
currentStream.getTracks().forEach(track => {
track.stop();
});
video.srcObject = null;
navigator.mediaDevices.getUserMedia({
audio: false,
video: {
deviceId: {
exact: cameras[camId]
}
}
}).then(successCallback).catch(errorCallback);
}
}
});
}
});