-
Notifications
You must be signed in to change notification settings - Fork 0
/
getUserMedia.js
98 lines (79 loc) · 2.79 KB
/
getUserMedia.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
'use strict';
import {Platform, NativeModules} from 'react-native';
import * as RTCUtil from './RTCUtil';
import MediaStream from './MediaStream';
import MediaStreamError from './MediaStreamError';
import permissions from './Permissions';
const { WebRTCModule } = NativeModules;
export default function getUserMedia(constraints = {}) {
// According to
// https://www.w3.org/TR/mediacapture-streams/#dom-mediadevices-getusermedia,
// the constraints argument is a dictionary of type MediaStreamConstraints.
if (typeof constraints !== 'object') {
return Promise.reject(new TypeError('constraints is not a dictionary'));
}
if ((typeof constraints.audio === 'undefined' || !constraints.audio)
&& (typeof constraints.video === 'undefined' || !constraints.video)) {
return Promise.reject(new TypeError('audio and/or video is required'));
}
// Normalize constraints.
constraints = RTCUtil.normalizeConstraints(constraints);
// Request required permissions
const reqPermissions = [];
if (constraints.audio) {
reqPermissions.push(permissions.request({ name: 'microphone' }));
} else {
reqPermissions.push(Promise.resolve(false));
}
if (constraints.video) {
reqPermissions.push(permissions.request({ name: 'camera' }));
} else {
reqPermissions.push(Promise.resolve(false));
}
return new Promise((resolve, reject) => {
Promise.all(reqPermissions).then(results => {
const [ audioPerm, videoPerm ] = results;
// Check permission results and remove unneeded permissions.
if (!audioPerm && !videoPerm) {
// https://www.w3.org/TR/mediacapture-streams/#dom-mediadevices-getusermedia
// step 4
const error = {
message: 'Permission denied.',
name: 'SecurityError'
};
reject(new MediaStreamError(error));
return;
}
audioPerm || (delete constraints.audio);
videoPerm || (delete constraints.video);
const success = (id, tracks) => {
// Store initial constraints.
for (const trackInfo of tracks) {
const c = constraints[trackInfo.kind];
if (typeof c === 'object') {
trackInfo.constraints = RTCUtil.deepClone(c);
}
}
const info = {
streamId: id,
streamReactTag: id,
tracks
};
resolve(new MediaStream(info));
};
const failure = (type, message) => {
let error;
switch (type) {
case 'TypeError':
error = new TypeError(message);
break;
}
if (!error) {
error = new MediaStreamError({ message, name: type });
}
reject(error);
};
WebRTCModule.getUserMedia(constraints, success, failure);
});
});
}