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.
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:
_job = new LiveJob();
_deviceSource = _job.AddDeviceSource(video, audio);
_deviceSource.PreviewWindow = new PreviewWindow(new HandleRef(panel1, panel1.Handle));
_job.ActivateSource(_deviceSource);
Here is the code to record the video and audio to a .wmv file:
FileArchivePublishFormat fileOut = new FileArchivePublishFormat();
fileOut.OutputFileName = String.Format("C:\\WebCam{0:yyyyMMdd_hhmmss}.wmv", DateTime.Now);
_job.PublishFormats.Add(fileOut);
_job.StartEncoding();
Streaming the webcam over the network
Here is the code to stream the video (and audio) of your webcam over the network:
_job = new LiveJob();
_deviceSource = _job.AddDeviceSource(video, audio);
_job.ActivateSource(_deviceSource);
_job.ApplyPreset(LivePresets.VC1256kDSL16x9);
PullBroadcastPublishFormat format = new PullBroadcastPublishFormat();
format.BroadcastPort = 8080;
format.MaximumNumberOfConnections = 2;
_job.PublishFormats.Add(format);
_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 :-)