Using Web Cam With Silverlight 5 To Capture Video

Microsoft released Silverlight 5 Beta recently. A lot of changes have been around improments in graphics rendering and multimedia support. So I decided to give Silverlight 5 Beta a spin and have some fun. And the first thing came to my mind was to quickly check if my previous application to access web cam using Silverlight still works or not.

web cam using silverlight 5

This post is quick tutorial that shows how to use Silverlight 5.0 to capture videos using web cam. Before you write any code, make sure that you have your web cam attached to your development machine. Here is sample code snippet that shows how to initiate capturing of video using web cam.

private void CaptureVideo_Click(object sender, RoutedEventArgs e)
   bool youGotPermission = false;
   // Do we have permission to access device.
   if (!CaptureDeviceConfiguration.AllowedDeviceAccess)
      // Ask user for permission to access devices.
      if (CaptureDeviceConfiguration.RequestDeviceAccess())
         youGotPermission = true;
   if (!youGotPermission) { return; }
   // Check what all devices we got!
   var devices = CaptureDeviceConfiguration.GetAvailableAudioCaptureDevices();
   var defaultVideoDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();
   if (defaultVideoDevice != null)
      var videoSource = new CaptureSource();
      videoSource.VideoCaptureDevice = defaultVideoDevice;
      videoBrush.Stretch = Stretch.Uniform;
      VideoShowWindow.Fill = videoBrush;

The code is a event handler that gets invoked when user clicks on a button on my page. Silverlight does not automatically starts capturing video streams even if there is a web cam attached. A user has to allow access to the device first. It is good thing that Silverlight has this security and check in place. Otherwise a application will automatically start capturing videos when you access the page. Well, it does not need any explanation why it is a good thing.

By calling RequestDeviceAccess, silverlight presents user with a dialog box requesting permission to access camera or video device on your machine. There is a check box that a user can click so that Silverlight can remember your choice. Otherwise user will be presented with that dialog box every single time.

Once silverlight has the permission, code is getting default device. It then creates a video brush and then attaches it to a rectangle that I have on my page. In few lines of code I was up and running with Silverlight 5 Beta to use web cam.




0.0 °C / 32.1 °F

weather conditions Clouds

Monthly Posts

Blog Tags