Click here to Skip to main content
15,888,350 members
Articles / Programming Languages / C#

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

Rate me:
Please Sign up or sign in to vote.
4.86/5 (77 votes)
4 Jul 2011CPOL1 min read 716.6K   39.5K   190   157
How to use a webcam in C#.

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:

C#
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:

C#
// 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:

C#
// 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:

C#
// 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:

XML
<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)


Written By
Software Developer
Italy Italy
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
Member 1585590930-Jan-23 20:54
Member 1585590930-Jan-23 20:54 
QuestionHi how to set crossbar video input (use EasyCap)? Pin
letinh100029-Apr-22 15:18
letinh100029-Apr-22 15:18 
QuestionBug in the demo Pin
Member 1361394030-Aug-18 23:28
Member 1361394030-Aug-18 23:28 
QuestionWPF demo is empty, is a joke? Pin
Ejrr108521-Jun-18 10:24
Ejrr108521-Jun-18 10:24 
QuestionAudio does not work Pin
Member 135588078-Dec-17 0:13
Member 135588078-Dec-17 0:13 
Questiongetting error "The type or namespace name 'Expression' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)" Pin
Member 106417797-Nov-16 19:17
Member 106417797-Nov-16 19:17 
QuestionError on EncoderDevices.FindDevices(EncoderDeviceType.Video) Pin
Manuel Eduardo Canepa Cihuelo24-Sep-16 7:57
professionalManuel Eduardo Canepa Cihuelo24-Sep-16 7:57 
QuestionError when live camera Pin
Member 1019731424-Aug-16 22:56
Member 1019731424-Aug-16 22:56 
Questionpreview window always got still image or black image Pin
arfken030917-May-16 20:46
arfken030917-May-16 20:46 
AnswerRe: preview window always got still image or black image Pin
mth13479-Dec-20 0:07
mth13479-Dec-20 0:07 
QuestionStrange behaviour Pin
Zmuro16-Oct-15 2:38
Zmuro16-Oct-15 2:38 
QuestionHow can I access the video from a web page? Pin
Member 113118281-Mar-15 12:01
Member 113118281-Mar-15 12:01 
QuestionSystem.Deployment.Application.InvalidDeploymentException Pin
Jirka Šáda2-Feb-15 5:18
Jirka Šáda2-Feb-15 5:18 
QuestionScreen Capture Pin
fazilamehtab13-Oct-14 22:24
fazilamehtab13-Oct-14 22:24 
AnswerRe: Screen Capture Pin
Mehdi Rostami22-Oct-14 8:30
Mehdi Rostami22-Oct-14 8:30 
QuestionPlease Help me Pin
AlbertusChW9-Sep-14 6:22
AlbertusChW9-Sep-14 6:22 
First thank you for your code.
Sorry for my bad english. I want to use some of your code, i just want to capture video from my webcam and take snapshot from it and i'll add some code for my program to control Autodesk Inventor API. But i still confuse about recode language from your code to my Visual Studio Express 2013 for Windows Dekstop, windows form application VB. Here are your code that i was edit:
VB
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Linq
Imports System.Text
Imports System.Windows.Forms
Imports System.Runtime.InteropServices
Imports System.Diagnostics

'Reference path for the following assemblies --> C:\Program Files\Microsoft Expression\Encoder 4\SDK\
Imports Microsoft.Expression.Encoder.Devices
Imports Microsoft.Expression.Encoder.Live
Imports Microsoft.Expression.Encoder

Public Class Form1
    Private LiveJob As Global.Microsoft.Expression.Encoder.Live.LiveJob
    Private LiveDeviceSource As LiveDeviceSource
    'Private bStartedRecording As Boolean = False

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ListBox1.ClearSelected()
        For Each edv In EncoderDevices.FindDevices(EncoderDeviceType.Video)
            ListBox1.Items.Add(edv.Name)
        Next

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If (ListBox1.SelectedIndex < 0) Then
            MessageBox.Show("No Video capture devices have been selected.\nSelect a video devices from the listboxes and try again.", "Warning")
            Return
        End If

        Dim audio As LiveDeviceSource.EnableInputAudioLine(x)
        For Each edv In EncoderDevices.FindDevices(EncoderDeviceType.Video)
            If (String.Compare(edv.Name, ListBox1.SelectedItem.ToString()) = 0) Then
                video = edv
                'break()

                'Checks for a/v devices
                LiveDeviceSource = LiveJob.AddDeviceSource(edv, audio)

                'No
                'Setup the video resolution and frame rate of the video device
                'NOTE: Of course, the resolution and frame rate you specify must be supported by the device!
                'NOTE2: May be not all video devices support this call, and so it just doesn't work, as if you don't call it (no error is raised)
                'NOTE3: As a workaround, if the .PickBestVideoFormat method doesn't work, you could force the resolution in the 
                'following instructions (called few lines belows): 'panelVideoPreview.Size=' and '_job.OutputFormat.VideoProfile.Size=' 
                'to be the one you choosed (640, 480).
                LiveDeviceSource.PickBestVideoFormat(New Size(640, 480), 15)

                'Get the properties of the device video
                Dim sp As SourceProperties = LiveDeviceSource.SourcePropertiesSnapshot()

                'Resize the preview panel to match the video device resolution set
                Panel1.Size = New Size(sp.Size.Width, sp.Size.Height)

                'Setup the output video resolution file as the preview
                LiveJob.OutputFormat.VideoProfile.Size = New Size(sp.Size.Width, sp.Size.Height)

                'Sets preview window to winform panel hosted by xaml window
                'PreviewWindow = New PreviewWindow(New HandleRef(Panel1, Panel1.Handle))

                'Make this source the active one
                LiveJob.ActivateSource(LiveDeviceSource)

                'Button1.Enabled = True
            End If
        Next


    End Sub
End Class


My problem are: 1. how to remove audio option. I try with "Dim audio As LiveDeviceSource.EnableInputAudioLine(x)" but i dont know about the value of integer x
2. Variable video is not declared. I try to declare it with string, integer, boolean, char cannot work either
3. Can you make stop capture more friendly code? because i cant found how to use NULL option in VB

Thx
Albertus Chandra Wijayanto
Mechanical Engineering
University Indonesia
+62 8811898921
albertuschw@yahoo.com

QuestionHey there. Pin
Member 104321188-Jun-14 4:21
Member 104321188-Jun-14 4:21 
Questionstart stop recording button only makes one file which is latest recorded Pin
Member 801762717-Apr-14 20:55
Member 801762717-Apr-14 20:55 
AnswerRe: start stop recording button only makes one file which is latest recorded Pin
Member 111690743-Nov-14 22:03
Member 111690743-Nov-14 22:03 
Questionstart encoding Pin
badi2386-Apr-14 21:57
badi2386-Apr-14 21:57 
AnswerRe: start encoding Pin
HugoAmi23-Sep-14 16:02
HugoAmi23-Sep-14 16:02 
Generalwebcam capture Pin
rakdosss2-Apr-14 5:52
rakdosss2-Apr-14 5:52 
QuestionStrong Delay Pin
erebos00717-Feb-14 12:42
erebos00717-Feb-14 12:42 
AnswerRe: Strong Delay Pin
selfwalker23-Jun-14 23:33
selfwalker23-Jun-14 23:33 
GeneralRe: Strong Delay Pin
Amir No-Family14-Jun-17 3:41
Amir No-Family14-Jun-17 3:41 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.