mandag den 4. juni 2012

Live c# video streaming webcam server and client

I wanted to capture live video from a webcam and stream it directly to a client application. This was thought to be for a robot which would stream video from its webcam eyes and allow me to see what the robot sees, but really it would be possible to build a cheap DIY home surveillance network around this.

The VS 2010 c# solution holds two projects, one commandline project for the server and one windows forms project for the client.

The server stream not video, but rather a series of captures images, but in presenting these images in a rapid fashion the end result will seem like a naturally flowing video stream. The images  made available to a connecting client IP by an initialized WCF service, namely via a tcp/ip binding. The images capture is done by utilizing the AForge framework to access an available webcam. The images are saved to disk and not to memory, as I wanted to retain the option of going through them again at a later point. The last captured image is always kept in memory, to be delivered to the calling client as the WCF's 'getWebCamImage()' method is invoked.

I set the web cam framerate to 15 frames per second, which is fine enough to moving images. The maximum number of images the human eye can distinguish is 30 per second, so I'm told, so 15 images per second makes for a comfortably video experience.

The client creates an instance of the WCF service. A timer is set to call the service and return an image-stream, which is placed into a standard winforms picturebox. In the example code the timer is set at 100 milliseconds, which will yield only 10 images per second - thus not the 15 frames which are actually captured, I did this to perserve bandwidth but in reality it should be perfectly possible to call the timer 15 times per second. The viewing experience is nice enough just the same.

Check out the source code below if you're in need of something like this. Please bear with all the references to 'robot this' and 'robot that', the functionality was meant for a robot control project. The WCF service runs localhost, but you would of course in due time seperate the client from the server and allow the service to run via an external IP, firewall-configured to the port of your choice and not my standard port no 8733.

Link to solution source code

Let me know if there's anything I can do to help you in implementing the project, if it gives you any trouble.

Hope this helps you!

Buy me a coffeeBuy me a coffee