Search code examples
javascriptwindowscamerawinjs

How to initialize the camera correctly in Windows 8?


I am trying to initialize the camera on windows 8. I have enabled the webcam capability in the project and on my windows 8 device as well.

Here is my code:

var dialog = new Windows.Media.Capture.CameraCaptureUI();
var aspectRatio = { width: 1, height: 1 };

dialog.photoSettings.croppedAspectRatio = aspectRatio;
dialog.captureFileAsync(Windows.Media.Capture.CameraCaptureUIMode.photo).done(function (file) {
    if (file) {
        editPreviewPicture(file);
        mainApp.pictureAccept('control');
    } else {

    }
}, function (e) {
    console.log("Error while opening camera: ", e);
});

On the line with 'captureFileAsync' I get the following error:

Runtime-error JavaScript: Access Denied.

I have double checked everything that is needed, even downloaded the sample project to check the code and test the camera, everything worked fine in that project.

Thanks in advance.


Solution

  • I found the problem.

    The above function was in this code block:

    WinJS.UI.Pages.define("/pages/queue/view.html", {
    
        ready: function (element, options) {
    
        }
    }
    

    The problem is: The ready callback is for the DOM elements and not for javascript, so it was still processing aSync code, and WinJS can't handle multiple aSync processes properly. That's why I got 'Access denied'.

    Now to fix this. You need to create a promise with a timeOut, like so:

    WinJS.Promise.timeout(500).then(
        function (complete) {
            // Camera initialization / Other aSync code here
        },
    
        function (error) { }
     );
    

    Hope this helps some people!