Created
November 16, 2018 05:49
-
-
Save bradley/f17bcef01ac27e0abbc84792a410c0bf to your computer and use it in GitHub Desktop.
Detect User Media Devices and Permission
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UserMediaDetector { | |
// Returns info on all user media devices in successful promise resolve. | |
getDevices() { | |
return new Promise((resolve, reject) => { | |
if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) { | |
reject(Error("UserMediaDetector getDevices failed: enumerateDevices is not supported")); | |
return; | |
} | |
navigator.mediaDevices.enumerateDevices() | |
.then(devices => { | |
resolve(devices.map( | |
({ deviceId, groupId, kind, label }) => ({ deviceId, groupId, kind, label }) | |
)); | |
}) | |
.catch(reject); | |
}); | |
}; | |
// Returns permitted status of given user media kind in successful promise resolve. | |
permitted(kind) { | |
return new Promise((resolve, reject) => { | |
if (!kind || !Object.values(UserMediaDetector.Kinds).includes(kind)) { | |
reject(Error(`UserMediaDetector permitted failed: kind ${kind} is not supported`)); | |
return; | |
} | |
this.getDevices() | |
.then(devices => { | |
// Note: The presence of a `label` on a device indicates that it | |
// the device is active or persistent permissions are granted. | |
const permitted = !!devices.find( | |
device => device.kind === kind && !!device.label | |
); | |
resolve(permitted); | |
}) | |
.catch(reject); | |
}); | |
}; | |
// Returns boolean value designating if all given media kinds are permitted in successful promise resolve. | |
permittedAll(kinds = Object.values(UserMediaDetector.Kinds)) { | |
return new Promise((resolve, reject) => { | |
const kindsArray = Array.isArray(kinds) ? kinds : Array.of(kinds); | |
const promises = kindsArray.map(kind => this.permitted(kind)); | |
Promise.all(promises) | |
.then(permissionStates => | |
resolve(permissionStates.every(isPermitted => isPermitted)) | |
) | |
.catch(reject); | |
}); | |
}; | |
} | |
UserMediaDetector.Kinds = { | |
VideoInput: "videoinput", | |
AudioInput: "audioinput", | |
AudioOutput: "audioinput" | |
}; | |
export default UserMediaDetector; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage: