Skip to content

Instantly share code, notes, and snippets.

@kylemcdonald
Last active May 30, 2019 01:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kylemcdonald/461b7c131578ea9fe75f9efd41184ba3 to your computer and use it in GitHub Desktop.
Save kylemcdonald/461b7c131578ea9fe75f9efd41184ba3 to your computer and use it in GitHub Desktop.
Some things that can go wrong when setting up a camera with getUserMedia.
function cameraReady(videoElement) {
console.log('cameraReady: checking...');
if (videoElement) {
if (videoElement.srcObject) {
let tracks = videoElement.srcObject.getVideoTracks();
if (tracks.length > 0) {
if (tracks[0].readyState == 'live') {
let w = videoElement.videoWidth, h = videoElement.videoHeight;
if (w > 0 || h > 0) {
console.log('cameraReady: live! ' + w + 'x' + h);
return true;
}
console.error('cameraReady: live, but 0x0');
return false;
}
console.error('cameraReady: readyState is ' + tracks[0].readyState);
return false;
}
console.error('cameraReady: no tracks');
return false;
}
console.error('cameraReady: no srcObject');
return false;
}
console.error('cameraReady: no element');
return false;
}
function initCamera(videoElement) {
// these are essential on iOS
videoElement.setAttributeNode(document.createAttribute('autoplay'));
videoElement.setAttributeNode(document.createAttribute('playsinline'));
// don't re-initialize the camera if it's already live
if (cameraReady(videoElement)) {
console.log('initCamera: done!');
return Promise.resolve();
}
return navigator.mediaDevices
.getUserMedia({
audio: false,
video: { facingMode: 'user' }
})
// stream is ready, set to the video element
// don't return until the metadata is ready
// https://stackoverflow.com/a/41866914/940196
.then(stream => new Promise(resolve => {
console.log('initCamera: setting srcObject...');
videoElement.onloadedmetadata = resolve;
videoElement.srcObject = stream;
}))
.then(() => console.log('initCamera: done!'))
.catch(err => {
console.error(err);
alert(config.cameraErrorMessage);
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment