I recently created a webcam directive in AngularJS that utilizes a service. For reference, I followed this example:
Surprisingly, the example works perfectly on my tablet, but when I integrate the code into my tablet's Google Chrome browser, it encounters a few bugs.
Bug #1: The rear camera fails to function.
Bug #2: Upon starting the camera directive, only the first frame of the stream is displayed and then it freezes. Strangely, switching to the non-functional rear camera and back causes the stream to appear.
Could someone point out where I might be going wrong? I've attempted several solutions without success.
This is the code for the webcam directive:
link: function postLink($scope, element) {
var videoSources = [];
MediaStreamTrack.getSources(function(mediaSources) {
for (var i = 0; i < mediaSources.length; i++)
{
if (mediaSources[i].kind == 'video')
{
videoSources.push(mediaSources[i].id);
}
}
if (videoSources.length > 1){ $scope.$emit('multipleVideoSources'); }
initCamera(0);
});
// Elements
var videoElement = element.find('video')[0];
// Stream
function streaming(stream) {
$scope.$apply(function(){
videoElement.src = stream;
videoElement.play();
});
}
// Check ready state
function checkReadyState(){
if (videoElement.readyState == 4)
{
$interval.cancel(interval);
$scope.$emit('videoStreaming');
}
}
var interval = $interval(checkReadyState, 1000);
// Init
$scope.$on('init', function(event, stream){
streaming(stream);
});
// Switch camera
$scope.$on('switchCamera', function(event, cameraIndex){
initCamera(cameraIndex);
});
// Init via Service
function initCamera(cameraIndex)
{
var constraints = {
audio: false,
video: {
optional: [{ sourceId: videoSources[cameraIndex] }]
}
};
camera.setup(constraints, camera.onSuccess, camera.onError);
}
}
Here is the code for the Camera service:
.service('camera', function($rootScope) {
// Setup of stream
this.init = false;
this.onError = function(error){
console.log(error);
alert('Camera error');
};
this.onSuccess = function(stream){
window.stream = stream;
stream = window.URL.createObjectURL(stream);
$rootScope.$broadcast('init', stream);
};
this.setup = function(constraint){
navigator.getMedia(constraint, this.onSuccess, this.onError);
this.init = true;
};
It works flawlessly on my laptop, though testing with multiple video sources is not possible due to having just one.