HTML5 video capture from browser: error with "stop() not a function"

A quick blog post about recent changes in the MediaStream API support in modern browsers. I had previously developed a function allowing users to capture images from their webcam, based on tutorials found on the web.

Here was my code to initialize the capture canvas:

function CaptureImageBeginCapture() {
   CaptureImageCanvas = $("#ImageCaptureCanvas")[0];
   var videoObj = { "video": true },
      errBack = function(error) {
         console.log("Video capture error: ", error.code);
      };

   CaptureImageVideo = $("#ImageCapturePreviewFrame")[0];
   CaptureImageContext = CaptureImageCanvas.getContext("2d");

   // Put video listeners into place   if(navigator.getUserMedia) { // Standard      navigator.getUserMedia(videoObj, function(stream) {
         CaptureImageStream = stream;
         CaptureImageVideo.src = stream;
         CaptureImageVideo.play();
      }, errBack);
   } else if(navigator.webkitGetUserMedia) { // WebKit-prefixed      navigator.webkitGetUserMedia(videoObj, function(stream){
         CaptureImageStream = stream;
         CaptureImageVideo.src = window.webkitURL.createObjectURL(stream);
         CaptureImageVideo.play();
      }, errBack);
   }
   else if(navigator.mozGetUserMedia) { // Firefox-prefixed      navigator.mozGetUserMedia(videoObj, function(stream){
         CaptureImageStream = stream;
         CaptureImageVideo.src = window.URL.createObjectURL(stream);
         CaptureImageVideo.play();
      }, errBack);
   }
}
And this code was used to react to the pressing of a "Capture" button which froze the image and then saved it.
// Snapping up the picture$("#ImageCaptureSnap").click(function() {
   CaptureImageContext.drawImage(CaptureImageVideo, 0, 0, 640, 480, -95,0,448,330);
   CaptureImageStream.stop();
   $("#ImageCaptureStep1").hide();
   $("#ImageCaptureStep2").show();
});
Unfortunately, the MediaStream.stop() function recently became depreciated. After a quick search, I found only one article explaining what I need to do to fix it. The fix is to get a "track" instance from your MediaStream and stop the track instead of stopping the MediaStream itself.
// Snapping up the picture$("#ImageCaptureSnap").click(function() {
   CaptureImageContext.drawImage(CaptureImageVideo, 0, 0, 640, 480, -95,0,448,330);
   try { CaptureImageStream.stop(); } catch(e) { }
   try {
       var track = CaptureImageStream.getTracks()[0];
       track.stop();
} catch(e) { }
$("#ImageCaptureStep1").hide(); $("#ImageCaptureStep2").show(); });
Hopefully it won't change further, but as we know HTML5 APIs are evolving all the time.

Comments

Popular posts from this blog

Affiliate module for Interspire Shopping Cart

How to fix: Outlook on iOS/iPhone: "No Internet Connection"

Dealing with Nginx 400 Bad Request HTTP errors