Skip to content

Instantly share code, notes, and snippets.

@tiagopotencia
Created May 6, 2018 19:22
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 tiagopotencia/df0a351260d7dc009534c55244cfb972 to your computer and use it in GitHub Desktop.
Save tiagopotencia/df0a351260d7dc009534c55244cfb972 to your computer and use it in GitHub Desktop.
var videoElement = undefined;
var videoSelect = undefined;
var cameras = [];
jQuery(document).ready(function(){
jQuery('#btn-change-camera').on('click', function(){
changeCamera(cameras);
})
videoElement = document.querySelector('video');
videoSelect = document.querySelector('select#videoSource');
navigator.mediaDevices.enumerateDevices()
.then(gotDevices).then(getStream(cameras)).catch(handleError);
});
function gotDevices(deviceInfos) {
for (var i = 0; i !== deviceInfos.length; ++i) {
var deviceInfo = deviceInfos[i];
if (deviceInfo.kind === 'videoinput') {
cameras.push(deviceInfo.deviceId);
}
}
}
function getStream(cameras) {
if (window.stream) {
window.stream.getTracks().forEach(function(track) {
track.stop();
});
}
var constraints = {
video: {
deviceId: {exact: cameras[0]}
}
};
navigator.mediaDevices.getUserMedia(constraints).
then(gotStream).catch(handleError);
}
function gotStream(stream) {
window.stream = stream; // make stream available to console
videoElement.srcObject = stream;
}
function handleError(error) {
console.log('Error: ', error);
}
function changeCamera(camera) {
var cameraToPush = cameras.shift()
getStream(cameras)
cameras.push(cameraToPush)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment