Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* Illustrates how to handle getting the correct deviceId for
* a user's stored preference, while accounting for Safari's
* security protocol of serving a random deviceId per page load.
*/
// These would be pulled from some persistent storage...
var storedVideoDeviceId = '1234';
var storedVideoDeviceLabel = 'Front camera';
function getDeviceId(devices) {
var videoDeviceId;
// Try matching by ID first.
for (var i = 0; i < devices.length; ++i) {
var device = devices[i];
console.log(device.kind + ": " + device.label + " id = " + device.deviceId);
if (deviceInfo.kind === 'videoinput') {
if (device.deviceId == storedVideoDeviceId) {
videoDeviceId = device.deviceId;
break;
}
}
}
if (!videoDeviceId) {
// Next try matching by label.
for (var i = 0; i < devices.length; ++i) {
var device = devices[i];
if (deviceInfo.kind === 'videoinput') {
if (device.label == storedVideoDeviceLabel) {
videoDeviceId = device.deviceId;
break;
}
}
}
// Sensible default.
if (!videoDeviceId) {
videoDeviceId = devices[0].deviceId;
}
}
// Now, the discovered deviceId can be used in getUserMedia() requests.
var constraints = {
audio: true,
video: {
deviceId: {
exact: videoDeviceId,
},
},
};
navigator.mediaDevices.getUserMedia(constraints).
then(function(stream) {
// Do something with the stream...
}).catch(function(error) {
console.error('getUserMedia() error: ', error);
});
}
function handleSuccess(stream) {
stream.getTracks().forEach(function(track) {
track.stop();
});
navigator.mediaDevices.enumerateDevices().
then(getDeviceId).catch(function(error) {
console.error('enumerateDevices() error: ', error);
});
}
// Safari requires the user to grant device access before providing
// all necessary device info, so do that first.
var constraints = {
audio: true,
video: true,
};
navigator.mediaDevices.getUserMedia(constraints).
then(handleSuccess).catch(function(error) {
console.error('getUserMedia() error: ', error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment