Monday, May 06, 2013

WinJS MediaCapture Showing Previously Taken Photo Issue

In a Windows 8 store app we use video tag to show the live preview:

HTML:

<video id="cameraPreview"></video>
JavaScript:
    var mediaCapture = new Windows.Media.Capture.MediaCapture();
    mediaCapture.initializeAsync().done(function () {
        cameraPreview.src = URL.createObjectURL(mediaCapture, { oneTimeOnly: true });
        cameraPreview.play();
    }

After taking a photo, we usually store the image in a temporary location and display it on the screen so the user can review it and decide next step e.g. retake the photo or save to picture library.

An issue occurs when reopen the MeidaCaputre object next time: the previously taken photo will display for a few seconds before the new live preview video starts playing. Here reopen means a new MediaCapture object is created and initialized, then pass it to the Video element.

This is very confusing to the user. How come we always see the image taken previously? It sounds like there's some image caching mechanism in MediaCapture. But I tried all MediaCapture's properties and methods and none of them helps. Finally I figured out the trick is to set the poster property of the Video element and it would resolve the problem. The Video element caches the last taken photo as the default background before the streaming video starts playing. When the poster property is set, it will display that poster image instead.

Following JavaScript sets the poster a 1x1 black Data URI image, then a black background will show up instead of the previously taken image.

    var black1x1DataUri = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw=="; 
    cameraPreview.poster = black1x1DataUri;