Click here to Skip to main content
Click here to Skip to main content

How to use a web cam in C# with .NET Framework 4.0 and Microsoft Expression Encoder 4

By , 4 Jul 2011
 

Screenshot_small.jpg

Introduction

If you are interested in using your webcam from C# in an easy way, this little article is for you. In order to achieve our goal, we need Microsoft .NET 4.0 and Microsoft Expression Encoder 4. You can get the latter for free, using the 'Microsoft Web Platform Installer', that can be downloaded from here: http://www.microsoft.com/web/downloads/platform.aspx.

Web_Platform_Installer_small.jpg

After that, we need to create a Windows Forms application and add the following references to the project:

Assembly Microsoft.Expression.Encoder
C:\Program Files\Microsoft Expression\Encoder 4\SDK\Microsoft.Expression.Encoder.dll

Assembly Microsoft.Expression.Encoder.Utilities
C:\Program Files\Microsoft Expression\Encoder 4\SDK\Microsoft.Expression.Encoder.Utilities.dll

Assembly Microsoft.Expression.Encoder.Types
C:\Program Files\Microsoft Expression\Encoder 4\SDK\Microsoft.Expression.Encoder.Types.dll

Using the Code

Here is the code to enumerate the video and audio devices:

foreach (EncoderDevice edv in EncoderDevices.FindDevices(EncoderDeviceType.Video))
{
     lstVideoDevices.Items.Add(edv.Name);
}
foreach (EncoderDevice eda in EncoderDevices.FindDevices(EncoderDeviceType.Audio))
{
     lstAudioDevices.Items.Add(eda.Name);
}

Here is the code to preview the video and the audio:

// Starts new job for preview window
_job = new LiveJob();

// Create a new device source. We use the first audio and video devices on the system
_deviceSource = _job.AddDeviceSource(video, audio);

// Sets preview window to winform panel hosted by xaml window
_deviceSource.PreviewWindow = new PreviewWindow(new HandleRef(panel1, panel1.Handle));

// Make this source the active one
_job.ActivateSource(_deviceSource);

Here is the code to record the video and audio to a .wmv file:

// Sets up publishing format for file archival type
FileArchivePublishFormat fileOut = new FileArchivePublishFormat();

// Sets file path and name
fileOut.OutputFileName = String.Format("C:\\WebCam{0:yyyyMMdd_hhmmss}.wmv", DateTime.Now);

// Adds the format to the job. You can add additional formats
// as well such as Publishing streams or broadcasting from a port
_job.PublishFormats.Add(fileOut);

// Start encoding
_job.StartEncoding();

Streaming the webcam over the network

Here is the code to stream the video (and audio) of your webcam over the network:

// Sets up publishing format for file archival type
_job = new LiveJob();

_deviceSource = _job.AddDeviceSource(video, audio);
_job.ActivateSource(_deviceSource);         

// Finds and applys a smooth streaming preset        
_job.ApplyPreset(LivePresets.VC1256kDSL16x9);

// Creates the publishing format for the job
PullBroadcastPublishFormat format = new PullBroadcastPublishFormat();
format.BroadcastPort = 8080;
format.MaximumNumberOfConnections = 2;

// Adds the publishing format to the job
_job.PublishFormats.Add(format);

// Starts encoding
_job.StartEncoding();

To view the broadcast, you can create a WPF application and use the MediaElement. It is just one line of code! Here is the whole code of the WPF application:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Show Broadcast" Height="350" Width="525">
    <Grid>
        <MediaElement Name="VideoControl" Source="http://localhost:8080" />
    </Grid>
</Window>

Conclusion

A piece of cake, isn't it? This is the new frontier of how to manage video and audio from C#. In the early days of C#, using a webcam was not so easy. I hope this will help those who want to play a bit with a webcam. Thanks for reading my first article :-)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Massimo Conti
Software Developer
Italy Italy
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 4membernaseer baloch1 May '13 - 22:13 
Good article.
QuestionNice Demo, but where is the audio when preview ?memberJohnson.Gao.12623 Apr '13 - 1:20 
Hi Massimo Conti,
 
Cool Demo, really nice!
 
But where is the audio when preview ? Would you please demo show how to play out audio using Expression? Actually preview is not just have a look without any audio. right ? THANKS
 
Johnson
Questionviewing stream on a remote computermemberMember 95262384 Apr '13 - 4:42 
I am not able to view the broadcast on a remote computer how do i go about it...!!
plzzz help me...!!
in desperate need for this...!!
Gaurav Sagwan

QuestionWebcam is showing black image in previewmemberMember 79864943 Apr '13 - 23:51 
I downloaded the application. It is working great!. But it works only for 4 times. Fifth time when I click on Preview button, it shows black screen in preview window. If I close the application and run it again then it works. but only 4 times. It does not work continuously.
 
Pleas help. It's an urgent.
 
Thanks
GeneralThanks!memberwcuthbertson8 Mar '13 - 9:52 
Nice demo! I have been searching for some example C# code for several days to help me manage my webcam for a work project. I was amazed at how few good examples were to be had, as I require both Video AND Audio capture. Most examples just do video or require 3rd party software or were actually wrappers from C++ (which I know, but not as well as C#). Your example doesn't do exactly what I need, but at least you got me started and hopefully I can find the remaining answers in the MS Expression Encoder docs.
My only suggestion would be that you post a link to those docs on this page, but I'm guessing I can find them without much trouble. Thanks again!
QuestionI am getting black screen while previwingmembersudheendra pavan sundar8 Mar '13 - 1:53 
Hi,
 
I downloaded and executed the code.
But, I am getting a black screen for preview.
While recording, I am able to record the videos.
 
Please help me.
QuestionHelpmembermakhondi4 Mar '13 - 6:22 
How do I display a text on the image. When recording is on file in?
QuestionError on winfows 8memberTub-9520 Feb '13 - 4:10 
Thanks for this projet. It works perfectly on Windows 7.
However, error occured on Windows 8 on Preview click button...
GeneralMy vote of 5memberWanararbrio16 Jan '13 - 9:33 
It is actually what I`m looking for ! =)
GeneralMy vote of 5memberXtErMiNaToR10210 Jan '13 - 23:56 
Great article!
Questionusing Microsoft.Expression.Encoder.Utilities; not found help mememberMember 964439429 Dec '12 - 19:10 
using Microsoft.Expression.Encoder.Utilities;
using Microsoft.Expression.Encoder.Types;
 
not found
 
i added the refernces but i not able to namespace in my project help me please
QuestionDoes not detect my usb Genius Camera Eye 312memberLuis Zeta4 Dec '12 - 5:39 
When i run the project it only shows "Screen Capture Source" , i have checked that the webcam is conected and working ok with other aplicaction such as skype etc
AnswerRe: Does not detect my usb Genius Camera Eye 312memberLuis Zeta4 Dec '12 - 6:22 
well i just realized that when i run from VS2010 it only detects screen capture device but if a i run the .exe file it detect my camera
QuestionWebcam detector in c#memberMember 798053425 Nov '12 - 18:28 
I was searching a solution for that to capture an image using c# windwosform . I Got the best solution from Code project. Thanks........Thumbs Up | :thumbsup: Thumbs Up | :thumbsup: Thumbs Up | :thumbsup:
QuestionIP cammemberrodey vincent22 Nov '12 - 19:17 
can EE4 capture and record video from ip camera?
QuestionAdjustement with wcfmemberAndéol_0014 Nov '12 - 5:45 
First of all i want to thank you for this article. It's very useful. And for fun i try to adjust it using wcf. Everything work fine except live screen capture streaming. I don't know what i really make wrong but after broadcasting the live screen capture i got video with black background wheras audio works perfectly.
Can you help me to fix my issue?
Thank.
GeneralMy vote of 4memberMember 94807894 Oct '12 - 16:30 
It works almost perfect...
QuestionUnable to create Devicememberharmurk20 Sep '12 - 3:15 
I got 2 webcams
If i use the "logitech C270" no problem
If i use the "logitech HD Pro C920" witch I want to use i get the follow error at:
 
_deviceSource = _job.AddDeviceSource(video, audio);
Unable to create Device. It may be in use or not functioning.
 
hopefully someone has an idea Smile | :)
QuestionHow to implement in existing projectmemberMember 943991418 Sep '12 - 12:43 
Hi, new to C# and Visual Studio here. I downloaded the source code but I only see frmEE4WebCam.cs, frmEE4WebCam.Designer.cs, frm$$4WebCam.resx, and Program.cs. Also, how do I implement this in an existing project?
QuestionLive video display in c# .netmemberMember 900485711 Jul '12 - 18:36 
Can u help me to do the same in c# .net frame work?
Questionincrustationmembergefkuz23 Jun '12 - 2:11 
Hello,
 
Good job. It's work well. But now I want to write something in front of the video and can't...
Label transparency doesn't work and drawstring doesn't anymore...
Have you some idea?
 
Thanks
Questionurgent please i need simple security camera application in c# or vb.netmemberkaydyonis21 Jun '12 - 8:39 
hi guys please help me my final year project
i need security camera system
that can detect four cameras
and start recording when detects a motion
and stop recording when motion became static
save recorded video to a folder with the date and hour
any idea or code
 
hint: i'm using vb2010 and 64 bit computer with windows 7 professional
Questionexcellent!memberShejn21 Jun '12 - 4:34 
this is exactly what I needed)Thanks
QuestionLiveJob [modified]memberweed2k14 Jun '12 - 4:06 
Hi,
great project - thanks!
 
I have a minor issue though. When I install the application on a secondary machine the application hangs when the _videoDevice is addded to the _job. The camera is properly connected and the _videoDevice is created properly.
 
Any clues?
 
_videoDevice = EncoderDevices.FindDevices(EncoderDeviceType.Video).Where(p => p.Name == "Digital microscope").FirstOrDefault();
_job = new LiveJob(); 
_deviceSource = _job.AddDeviceSource(_videoDevice, null);<--- Here
 
Cheers
/T


modified 14 Jun '12 - 11:37.

Questionbroadcast in internetmemberMember 802424911 Jun '12 - 1:16 
what are the modifications that i should made to broadcast this live video on the internet.please help me i need this for my university project...thanxxx
QuestionVideo is delay (lagging) after 1 minute running.memberrockblin7 Jun '12 - 16:17 
This source is really helpful for me Smile | :) Thank you :X
But I get a problem about video quality. It becomes lagging (delay image) after I run it for 1 minute.
Anybody have any ideas for this problem :(
QuestionRe: Video is delay (lagging) after 1 minute running.memberrockblin7 Jun '12 - 17:23 
One more thing, when I compile successful and I run it ok on my laptop (my webcam is actived). But I copy an exe file to another laptop, it doesn't work ? Do I need to install Microsoft Expression Encoder 4 into that laptop? Is it necessary?
QuestionResolutionmembermurillobraga7 Jun '12 - 9:50 
I wanna grab 1280x720 as I have a Microsoft HD-3000.
 
I tried to force
panelVideoPreview.Size = new Size(1280, 720);
_job.OutputFormat.VideoProfile.Size = new Size(1280, 720);
 
But it didn't work.
 
Any ideas?
 
Tks!
Questionsee streamed video in web sitememberMember 80242495 Jun '12 - 3:47 
thnks for the code i was looking for it.but i need to is there any way to see the steamed video in a website.like asp.net.because i need to see the video through web.thanx again...
QuestionGreat Projectmember665909018 May '12 - 10:52 
Thanks for your reply,and sorry my english
 
i start my university project "live stream over LAN" and your project help me ,can you help me on this project,or sned me tips for this project
QuestionCapturing Encode result to save in DataBasememberbkrussell18 May '12 - 3:21 
Great article,
 
Is there a way to use a database to save and retrieve the encoded result rather than a physical file.
GeneralRecord Button thrown Expectionmember665909011 May '12 - 3:22 
I can get my feed of Camera on this app but ,if i press Record Button ,app can thrown expection
 
Overall this app is awsome
GeneralRe: Record Button thrown ExpectionmemberMassimo Conti11 May '12 - 9:00 
I guess you have the UAC (User Accout Control) enabled.
If you need UAC enabled, try to run the application with 'Run as Administrator'.
You could also disable it and try again, or simply change where to save the stream, so NOT in C:\, but in your Document Folder.
 
I hope this helps.
QuestionVideo Delay and LagmemberMember 80802984 May '12 - 14:37 
first of all good job ! Smile | :) .. but streaming is giving a delay.. any suggestions on how to put performance better ? Also, how is decoding done on the receiving end?
GeneralMy vote of 5memberMohammad Sepahvand30 Apr '12 - 1:34 
Great work. Just a quick question. How would I go about converting the stream and the audio from LiveJob into a byte array/stream so that I can transmit it over a network with WCF? Thanks for any suggestions.
GeneralRe: My vote of 5memberMohammad Sepahvand4 May '12 - 22:46 
any ideas guys? is it at all possible to get the capture output as a Stream object?
GeneralMy vote of 5memberandyclass5027 Apr '12 - 12:13 
Simple and straight to the point, excellent !
QuestionExcellent! but had to change location where files saved tomemberfarvenkloodgen18 Apr '12 - 21:43 
Great piece of work!, but I had to change the folder where program saved to other than C:\ before the pics and vids actually got saved to my hard drive? I am running win 7 64 bit HP pavillion dv6 with updated OS and BIOS and C# Express as well, using the HP true Vision webcam integrated into the laptop. I changed to c:\\Users\\... and found them. Thank you Wink | ;) *****
BugCall to PickBestVideoFormat is wrongmemberChad Z. Hower aka Kudzu28 Mar '12 - 4:22 
You have 15 for the frame length param. But the param is not frame rate, it is frame LENGTH measured in 100ns units.. so for 15 fps you need to call this instead:
 
// Frame length is 100 ns units, so ns is 1,000,000,000, we took off 2 zeros to get 100 ns units
_deviceSource.PickBestVideoFormat(new Size(1280, 1024), 10000000 / 15);
Chad Z. Hower, a.k.a. Kudzu
"Programming is an art form that fights back"
 
My Technical Stuff:
http://www.KudzuWorld.com
 
My Blogs:
http://www.KudzuWorld.com/blogs/

GeneralRe: Call to PickBestVideoFormat is wrongmemberMassimo Conti28 Mar '12 - 11:22 
Yes, you are right, the second parameter is frameDuration:
 
The target frame duration to try to match, in 100 nano-second units.
 
http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=EN-US&k=k(MICROSOFT.EXPRESSION.ENCODER.LIVE.LIVEDEVICESOURCE.PICKBESTVIDEOFORMAT);k(PICKBESTVIDEOFORMAT)&rd=true[^]
 
My webcam has the following frame rate: 15
 
Anyway, using your formula sp.FrameRate.ToString() --> 15.000015000014999
Due to the fact that the data type is long, I used 15 directly.
Is this consideration wrong, also looking at that number ?
Does it make any difference?
 
Regards,
 
Massimo
GeneralRe: Call to PickBestVideoFormat is wrongmemberChad Z. Hower aka Kudzu28 Mar '12 - 11:25 
You cant use 15. Thats the frame rate. Instead you need to pass 10000000 / 15 for the value. That will give you the frame length for 15 fps. It will make a huge difference because passing 15 will ask for a frame rate of 666,666 frames per second... which is impossible so the call will never yield a match for your request.
Chad Z. Hower, a.k.a. Kudzu
"Programming is an art form that fights back"
 
My Technical Stuff:
http://www.KudzuWorld.com
 
My Blogs:
http://www.KudzuWorld.com/blogs/

GeneralRe: Call to PickBestVideoFormat is wrongmemberChad Z. Hower aka Kudzu28 Mar '12 - 15:50 
ie look closely.. the second argument is frame LENGTH.. not frame RATE.....
Chad Z. Hower, a.k.a. Kudzu
"Programming is an art form that fights back"
 
My Technical Stuff:
http://www.KudzuWorld.com
 
My Blogs:
http://www.KudzuWorld.com/blogs/

GeneralRe: Call to PickBestVideoFormat is wrongmemberMassimo Conti30 Mar '12 - 9:19 
Yes, you are right. I got it.
Thanks
QuestionHow to get a Handle to underlying stream of the MediaElement?memberMember 871481722 Mar '12 - 9:54 
Hi, I'm trying to use the streamed webcam on the receiving end to do Face Recognition, and cant find a way to make use of the MediaElement which is responsible for handling the http client side of the stream, and turning it into video.
 
I don't want/need a wpf app with a control and a video feed being constructed out of the http stream. Instead, I need to get a hold of the series of video frames on the receiving end, either as C# Image/Bitmap objects, or even as a byte[], which I can then turn into the Images.
 
Can I leverage the MediaElement to get a handle to those video frames, or do I need to reconstitute them myself?
Questionmy vote of 5member.NetStars21 Mar '12 - 1:28 
great article!
QuestionCapture image from streamingmemberEldoran4 Mar '12 - 6:51 
If you have a window over the window you want to capture the capture will be an image of the over window or if you minimize the window occurs the same, you'll capture a screenshot of the coordenates. This method is a capture of screen with coordenates.
 
How it would be the capture image of the streaming???

AnswerRe: Capture image from streamingmemberMassimo Conti4 Mar '12 - 10:54 
Actualy it seems it is not in the sdk yet the possibility to take a snapshot from a live straming. You could try to contact Microsoft. Anyway I thought about a solution in 5 minutes and I came out with the following:
 
// Add a new button to the form called 'btnGrabImage2' and double click on it.
// Add the code below for that method.
 
private void btnGrabImage2_Click(object sender, EventArgs e)
{
string strVideoFile;
 
btnGrabImage2.Enabled = false;
btnGrabImage2.Refresh();
 
FileArchivePublishFormat fileOut = new FileArchivePublishFormat();
strVideoFile = String.Format("C:\\WebCam{0:yyyyMMdd_hhmmss}.wmv", DateTime.Now);
fileOut.OutputFileName = strVideoFile;
 
_job.PublishFormats.Add(fileOut);
_job.StartEncoding();
 
try
{
Thread.Sleep(200);
 
_job.StopEncoding();
 
string strGrabFileName = String.Format("C:\\Snapshot2_{0:yyyyMMdd_hhmmss}.jpg", DateTime.Now);
toolStripStatusLabel1.Text = strGrabFileName;
 
var video = new MediaItem(strVideoFile);
using (var bitmap = video.MainMediaFile.GetThumbnail(new TimeSpan(0, 0, 1), new System.Drawing.Size(640, 480)))
{
bitmap.Save(strGrabFileName, System.Drawing.Imaging.ImageFormat.Jpeg);
}
 
btnGrabImage2.Enabled = true;
btnGrabImage2.Refresh();
}
catch (Exception ex)
{
toolStripStatusLabel1.Text = "Exception error in job_Status event --> " + ex.Message;
}
}
 

Basically the idea is this:
Let it start to capture the video streaming to file and after the fist frame stop it and take the first Thumbnail from that file.

I hope this help. Smile | :)
GeneralRe: Capture image from streamingmemberIvo Štimac16 Mar '12 - 3:54 
Thank you for this, it really helped me with a problem I was having. However, creating a media item from a file is a bit time consuming, is there any way to stream the video to an in-memory object and then taking a thumbnail from that object?
GeneralRe: Capture image from streamingmemberChad Z. Hower aka Kudzu28 Mar '12 - 3:17 
The current source I downloaded has this:
 
private void cmdGrabImage_Click(object sender, EventArgs e) {
// Create a Bitmap of the same dimension of panelVideoPreview (Width x Height)
using (Bitmap bitmap = new Bitmap(panelVideoPreview.Width, panelVideoPreview.Height)) {
using (Graphics g = Graphics.FromImage(bitmap)) {
// Get the paramters to call g.CopyFromScreen and get the image
Rectangle rectanglePanelVideoPreview = panelVideoPreview.Bounds;
Point sourcePoints = panelVideoPreview.PointToScreen(new Point(panelVideoPreview.ClientRectangle.X, panelVideoPreview.ClientRectangle.Y));
g.CopyFromScreen(sourcePoints, Point.Empty, rectanglePanelVideoPreview.Size);
}
 
string strGrabFileName = String.Format(@"d:\temp\Snapshot_{0:yyyyMMdd_hhmmss}.jpg", DateTime.Now);
toolStripStatusLabel1.Text = strGrabFileName;
bitmap.Save(strGrabFileName, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
Chad Z. Hower, a.k.a. Kudzu
"Programming is an art form that fights back"
 
My Technical Stuff:
http://www.KudzuWorld.com
 
My Blogs:
http://www.KudzuWorld.com/blogs/

GeneralRe: Capture image from streamingmemberMassimo Conti28 Mar '12 - 10:36 
Hello Chad Z. Hower aka Kudzu,
 
Yes that code does the grab image.
The problem is that if there is a windows over the panel (for example the notepad), you get it and not the picture that is below. May be the same problem could occur if the application is minimized and you want to grab the picture.
I hopw now you got the issue.
 
Regards,
 
Massimo.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 4 Jul 2011
Article Copyright 2011 by Massimo Conti
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid