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

WPF: Webcam Control

By , 11 Feb 2013
 
Prize winner in Competition "Best VB.NET article of November 2011"

WPF_WebcamControl/Screenshot_1.png

Introduction

I have on several occasions scoured the net for a simple to use WPF webcam control and either my search queries were awful or I just wasn't comfortable with whatever I found. This webcam interest was recently increased when I read an article, here on CodeProject, that referred to an application that made use of a webcam. It was a Silverlight article and the ease with which one could utilize a webcam in Silverlight made me envious of WPF's little brother (or is it sister?). The VideoBrush in Silverlight is especially a nice touch.

It is with this pain and envy in mind that I decided to try my hand at creating a WPF control that could;

  1. Display webcam video with little coding effort,
  2. Allow saving of webcam video to harddisk, with little coding effort,
  3. Save the webcam video in a variety of video formats

Background

With the previously mentioned goals in mind, I created a WPF UserControl that has the following features,

  • Displays webcam video,
  • Enables saving of webcam videos to harddisk,
  • Enables saving of webcam videos in either .wmv, .mp4, or .flv format

The UserControl also enables you to take a snapshot of the live webcam video, and save it as a Jpeg, Png, Gif, or any other of the ImageFormat properties.

The Webcam control makes heavy use of the Expression Encoder 4 SDK. You therefore need to have the SDK installed on your machine to make use of the UserControl. You can download the SDK from here.

Requirements

To make use of the Webcam control, you require;

  • .NET Framework 4.0
  • Expression Encoder SDK

Using the Webcam Control

To use the Webcam control in your WPF application add a reference to WebcamControl.dll and a using/Imports statement for WebcamControl at the top of your class.

Add a reference to Microsoft.Expression.Encoder.dll . Do this by using the Add Reference dialog box, selecting the .NET tab, and selecting Microsoft.Expression.Encoder from the listbox. The Expression Encoder assemblies should be available if you have installed Expression Encoder 4.

The following example, which is the downloadable sample application, shows the use of the Webcam control. The Webcam control is defined in the Window's XAML markup.

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:cam="clr-namespace:WebcamControl;assembly=WebcamControl"    
    ...
    >
    <Grid>
        <cam:Webcam Name="WebCamCtrl" Margin="12,12,12,204"></cam:Webcam>        
        ...
    </Grid>
</Window>

VB.NET

Imports Microsoft.Expression.Encoder.Devices
Imports WebcamControl
Imports System.IO
Imports Microsoft.Expression.Encoder.Live
Imports Microsoft.Expression.Encoder
Imports System.Drawing
Imports System.Drawing.Imaging

Class MainWindow

    ' Bind Webcam dependency properties to ComboBox property.   
    Private Sub MainWindow_Initialized(ByVal sender As Object, _
                                       ByVal e As System.EventArgs) Handles Me.Initialized
        Dim bndg_1 As New Binding("SelectedValue")
        bndg_1.Source = VidDvcsComboBox
        WebCamCtrl.SetBinding(Webcam.VideoDeviceProperty, bndg_1)

        Dim bndg_2 As New Binding("SelectedValue")
        bndg_2.Source = AudDvcsComboBox
        WebCamCtrl.SetBinding(Webcam.AudioDeviceProperty, bndg_2)
    End Sub

    Private Sub MainWindow_Loaded(ByVal sender As Object, _
                                  ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        FindDevices()

        Dim vidPath As String = "C:\VideoClips"
        Dim imgPath As String = "C:\WebcamSnapshots"

        If Directory.Exists(vidPath) = False Then
            Directory.CreateDirectory(vidPath)
        End If

        If Directory.Exists(imgPath) = False Then
            Directory.CreateDirectory(imgPath)
        End If

        ' Set some properties of the Webcam control.
        WebCamCtrl.VideoDirectory = vidPath
        WebCamCtrl.VidFormat = VideoFormat.mp4

        WebCamCtrl.ImageDirectory = imgPath
        WebCamCtrl.PictureFormat = ImageFormat.Jpeg
        
        WebCamCtrl.FrameRate = 30
        WebCamCtrl.FrameSize = New Size(320, 240)

        VidDvcsComboBox.SelectedIndex = 0
        AudDvcsComboBox.SelectedIndex = 0
    End Sub

    ' Find available a/v devices.
    Private Sub FindDevices()
        Dim vidDevices = EncoderDevices.FindDevices(EncoderDeviceType.Video)
        Dim audDevices = EncoderDevices.FindDevices(EncoderDeviceType.Audio)

        For Each dvc In vidDevices
            VidDvcsComboBox.Items.Add(dvc.Name)
        Next

        For Each dvc In audDevices
            AudDvcsComboBox.Items.Add(dvc.Name)
        Next
    End Sub

    Private Sub StartButton_Click(ByVal sender As System.Object, _
                                  ByVal e As System.Windows.RoutedEventArgs) _
                              Handles StartButton.Click
        ' Display webcam images on control.
        Try
            WebCamCtrl.StartCapture()
        Catch ex As Microsoft.Expression.Encoder.SystemErrorException
            MessageBox.Show("Device is in use by another application")
        End Try
    End Sub

    Private Sub EndButton_Click(ByVal sender As Object, _
                                ByVal e As System.Windows.RoutedEventArgs) _
                            Handles EndButton.Click
        ' Stop the display of webcam video.
        WebCamCtrl.StopCapture()
    End Sub

    Private Sub RecordButton_Click(ByVal sender As System.Object, _
                                   ByVal e As System.Windows.RoutedEventArgs) _
                               Handles RecordButton.Click
        ' Start recording of webcam video to harddisk.
        WebCamCtrl.StartRecording()
    End Sub

    Private Sub StopRecordButton_Click(ByVal sender As Object, _
                                       ByVal e As System.Windows.RoutedEventArgs) _
                                   Handles StopRecordButton.Click
        ' Stop recording of webcam video to harddisk.
        WebCamCtrl.StopRecording()
    End Sub

    Private Sub SnapshotButton_Click(ByVal sender As System.Object, _
                                     ByVal e As System.Windows.RoutedEventArgs) _
                                 Handles SnapshotButton.Click
        WebCamCtrl.TakeSnapshot()
    End Sub
End Class

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Expression.Encoder.Devices;
using WebcamControl;
using System.IO;
using System.Drawing.Imaging;

namespace WPF_Webcam
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        
        public MainWindow()
        {
            InitializeComponent();                    

            // Bind the Video and Audio device properties of the
            // Webcam control to the SelectedValue property of 
            // the necessary ComboBox.
            Binding bndg_1 = new Binding("SelectedValue");
            bndg_1.Source = VidDvcsComboBox;
            WebCamCtrl.SetBinding(Webcam.VideoDeviceProperty, bndg_1);

            Binding bndg_2 = new Binding("SelectedValue");
            bndg_2.Source = AudDvcsComboBox;
            WebCamCtrl.SetBinding(Webcam.AudioDeviceProperty, bndg_2);

            // Create directory for saving video files.
            string vidPath = @"C:\VideoClips";

            if (Directory.Exists(vidPath) == false)
            {
                Directory.CreateDirectory(vidPath);
            }

            // Create directory for saving image files.
            string imgPath = @"C:\WebcamSnapshots";

            if (Directory.Exists(imgPath) == false)
            {
                Directory.CreateDirectory(imgPath);
            }

            // Set some properties of the Webcam control
            WebCamCtrl.VideoDirectory = vidPath;
            WebCamCtrl.VidFormat = VideoFormat.mp4;

            WebCamCtrl.ImageDirectory = imgPath;
            WebCamCtrl.PictureFormat = ImageFormat.Jpeg;
                        
            WebCamCtrl.FrameRate = 30;
            WebCamCtrl.FrameSize = new System.Drawing.Size(320, 240);          

            // Find a/v devices connected to the machine.
            FindDevices();

            VidDvcsComboBox.SelectedIndex = 0;
            AudDvcsComboBox.SelectedIndex = 0;
        }

        private void FindDevices()
        {
            var vidDevices = EncoderDevices.FindDevices(EncoderDeviceType.Video);
            var audDevices = EncoderDevices.FindDevices(EncoderDeviceType.Audio);

            foreach (EncoderDevice dvc in vidDevices)
            {
                VidDvcsComboBox.Items.Add(dvc.Name);
            }

            foreach (EncoderDevice dvc in audDevices)
            {
                AudDvcsComboBox.Items.Add(dvc.Name);
            }

        }

        private void StartButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Display webcam video on control.
                WebCamCtrl.StartCapture();               
            }
            catch (Microsoft.Expression.Encoder.SystemErrorException ex)
            {
                MessageBox.Show("Device is in use by another application");
            }
        }

        private void EndButton_Click(object sender, RoutedEventArgs e)
        {
            // Stop the display of webcam video.
            WebCamCtrl.StopCapture();
        }

        private void RecordButton_Click(object sender, RoutedEventArgs e)
        {
            // Start recording of webcam video to harddisk.
            WebCamCtrl.StartRecording();
        }

        private void StopRecordButton_Click(object sender, RoutedEventArgs e)
        {
            // Stop recording of webcam video to harddisk.
            WebCamCtrl.StopRecording();
        }

        private void SnapshotButton_Click(object sender, RoutedEventArgs e)
        {
            // Take snapshot of webcam image.
            WebCamCtrl.TakeSnapshot();
        }           
       
    }
}

As you can see from the sample code using the Webcam control is not a hard affair once you have the necessary references and using/Imports statements.

Webcam

The following are the members of interest in class Webcam,

Properties

Name Description Type
WPF_WebcamControl/PropertyIcon.png VideoDirectory Gets or Sets the folder where the recorded webcam video will be saved. This is a dependency property. String
WPF_WebcamControl/PropertyIcon.png VidFormat Gets or Sets the video format in which the webcam video will be saved. This is a dependency property. (The default format is .wmv) VideoFormat
WPF_WebcamControl/PropertyIcon.png VideoDevice Gets or Sets the name of the video device to be used. This is a dependency property. String
WPF_WebcamControl/PropertyIcon.png AudioDevice Gets or Sets the name of the audio device to be used. This is a dependency property. String
WPF_WebcamControl/PropertyIcon.png IsRecording Gets a value indicating whether video recording is taking place. This is a read-only property. Boolean
WPF_WebcamControl/PropertyIcon.png ImageDirectory Gets or Sets the folder where a snapshot of the webcam video will be saved. This is a dependency property. String
WPF_WebcamControl/PropertyIcon.png PictureFormat Gets or Sets the format in which a snapshot of the webcam video will be saved. This is a dependency property. (The default format is Jpeg). ImageFormat
WPF_WebcamControl/PropertyIcon.png FrameRate Gets or sets the frame rate in frames per second. This is a dependency property. (The default value is 15). Integer
WPF_WebcamControl/PropertyIcon.png FrameSize Gets or sets the size of the video profile. This is a dependency property. (The default size is 320x240). System.Drawing.Size

Methods

Name Description
WPF_WebcamControl/MethodIcon.png StartCapture Displays webcam video on control. (Throws a Microsoft.Expression.Encoder.SystemErrorException if a specified device is already in use by another application)
WPF_WebcamControl/MethodIcon.png StopCapture Stops the capturing/display of webcam video. (Stops any current recording of webcam video)
WPF_WebcamControl/MethodIcon.png StartRecording Starts the recording of webcam video to a video file. (Throws a DirectoryNotFoundException if the directory specified in the VideoDirectory property does not exist)
WPF_WebcamControl/MethodIcon.png StopRecording Stops the recording of webcam video.  
WPF_WebcamControl/MethodIcon.png TakeSnapshot Saves a snapshot of the webcam video. (Throws a DirectoryNotFoundException if the directory specified in the ImageDirectory property does not exist)

The Code

The XAML markup for the UserControl is,

<UserControl x:Class="Webcam" 
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
             Height="Auto" Width="Auto" MinHeight="100" MinWidth="100" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
             mc:Ignorable="d" d:DesignWidth="320" d:DesignHeight="240" Name="Webcam">
    <Grid>
        <WindowsFormsHost Margin="0,0,0,0" Name="WinFormHost" Background="{x:Null}">
            <wf:Panel x:Name="WebcamPanel" Size="320,240" />
        </WindowsFormsHost>
    </Grid>
</UserControl>
The VideoDevice dependency property is defined as follows,

''' <summary>
''' Gets or Sets the name of the video device to be used.
''' </summary>    
Public Property VideoDevice() As String
    Get
        Return CType(GetValue(VideoDeviceProperty), String)
    End Get
    Set(ByVal value As String)
        SetValue(VideoDeviceProperty, value)
    End Set
End Property

Public Shared VideoDeviceProperty As DependencyProperty = _
    DependencyProperty.Register("VideoDevice", GetType(String), GetType(Webcam), _
                          New FrameworkPropertyMetadata(New PropertyChangedCallback( _
                                                              AddressOf VidDeviceChange)))

Private Shared Sub VidDeviceChange(ByVal source As DependencyObject, _
    ByVal e As DependencyPropertyChangedEventArgs)
    Dim deviceName As String = CType(e.NewValue, String)
    Dim eDev = EncoderDevices.FindDevices(EncoderDeviceType.Video).Where _
               (Function(dv) dv.Name = deviceName)

    If (eDev.Count > 0) Then
        CType(source, Webcam).vidDevice = eDev.First

        Try
            CType(source, Webcam).Display()
        Catch ex As Microsoft.Expression.Encoder.SystemErrorException
            Exit Sub
        End Try
    End If
End Sub

The StartCapture() method displays the webcam video in the WinForm Panel, if the necessary properties are set,

''' <summary>
''' Display webcam video on control.
''' </summary>
Public Sub StartCapture()
    If (canCapture = False) Then
        canCapture = True

        Try
            Display()
        Catch ex As Microsoft.Expression.Encoder.SystemErrorException
            canCapture = False
            Throw New Microsoft.Expression.Encoder.SystemErrorException
        End Try
    Else
        Exit Sub
    End If
End Sub
    
' Display video from webcam.
Private Sub Display()
    If (canCapture = True) Then
        If (vidDevice IsNot Nothing) Then
            StopRecording()
            Dispose()

            job = New LiveJob
            Dim frameDuration As Long = CLng(_frameRate * Math.Pow(10, 7))

            deviceSource = job.AddDeviceSource(vidDevice, audDevice)
            deviceSource.PickBestVideoFormat(_frameSize, frameDuration)
            WebcamPanel.Size = _frameSize
            job.OutputFormat.VideoProfile.Size = _frameSize
            deviceSource.PreviewWindow = New PreviewWindow(New HandleRef(WebcamPanel, WebcamPanel.Handle))

            job.ActivateSource(deviceSource)

            isCapturing = True
        End If
    End If
End Sub

The StartRecording() method records video from the webcam to the harddisk,

''' <summary>
''' Starts the recording of webcam video to a video file.
''' </summary>
Public Sub StartRecording()
    If (vidDirectory <> String.Empty AndAlso job IsNot Nothing) Then
        If (Directory.Exists(vidDirectory) = False) Then
            Throw New DirectoryNotFoundException("The specified directory does not exist")
            Exit Sub
        End If

        ' If isCapturing is true then it means the control is capturing images 
        ' from the webcam.
        If (isCapturing = True) Then
            StopRecording()
            job.PublishFormats.Clear()

            Dim timeStamp As String = DateTime.Now.ToString
            timeStamp = timeStamp.Replace("/", "-")
            timeStamp = timeStamp.Replace(":", ".")
            Dim filePath As String = vidDirectory & "\WebcamVid " & timeStamp & "." & _vidFormat.ToString

            Dim fileArchFormat As New FileArchivePublishFormat(filePath)
            job.PublishFormats.Add(fileArchFormat)
            job.StartEncoding()

            _isRecording = True
        End If
    End If
End Sub

The VideoFormat enumeration contains three members,

Public Enum VideoFormat
    wmv
    mp4
    flv
End Enum

The TakeSnapshot() method saves a snapshot of the webcam video. The image generated is actually a snapshot of the WinForms Panel, WebcamPanel. The size of the image will depend on the size of the Webcam control.

''' <summary>
''' Take snapshot of a webcam image. 
''' </summary>
Public Sub TakeSnapshot()
    If (imgDirectory <> String.Empty AndAlso job IsNot Nothing) Then
        If (Directory.Exists(imgDirectory) = False) Then
            Throw New DirectoryNotFoundException("The specified directory does not exist")
            Exit Sub
        End If

        ' If isCapturing is true then it means the control is capturing video 
        ' from the webcam.
        If (isCapturing = True) Then
            Dim panelWidth As Integer = CInt(Me.ActualWidth)
            Dim panelHeight As Integer = CInt(Me.ActualHeight)

            Dim timeStamp As String = DateTime.Now.ToString
            timeStamp = timeStamp.Replace("/", "-")
            timeStamp = timeStamp.Replace(":", ".")

            Dim filePath As String = imgDirectory & "\Snapshot " & timeStamp & "." & imgFormat.ToString

            Dim pnlPnt As Point = WebcamPanel.PointToScreen(New Point(WebcamPanel.ClientRectangle.X, _
                                                                      WebcamPanel.ClientRectangle.Y))

            Using bmp As New Bitmap(panelWidth, panelHeight)
                Using gcs As Graphics = Graphics.FromImage(bmp)
                    gcs.CopyFromScreen(pnlPnt, Point.Empty, New Size(panelWidth, panelHeight))
                End Using
                bmp.Save(filePath, imgFormat)
            End Using
        End If
    End If
End Sub

You can take a look at the other properties and methods defined in class Webcam by downloading the source files from the download link at the top of this article.

Conclusion

I hope that you picked up something useful from this article. I'm a novice in audio-video-encoding-decoding matters so if you have any questions regarding such technicalities, please try to post them in the associated forums here on CodeProject. Suggestions will be beneficial, as well as answers you receive to any technical queries that may be associated with this article's content. Thanks.

History

  • 18th Nov, 2011: Initial post
  • 19th Nov, 2011: Updated code
  • 31st Mar, 2012: Added snapshot feature.
  • 17th Nov, 2012: Added FrameRate and FrameSize properties.

License

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

About the Author

Meshack Musundi
Software Developer
Kenya Kenya
Member
Meshack is an avid programmer with a bias towards WPF and VB.NET. He currently resides in a small town in Kiambu county, Kenya.
 
Awards;
  • CodeProject MVP 2013
  • CodeProject MVP 2012
  • Best VB.NET article of February 2013
  • Best VB.NET article of October 2012
  • Best VB.NET article of July 2012
  • Best VB.NET article of February 2012
  • Best VB.NET article of January 2012
  • Best VB.NET article of November 2011
  • Best VB.NET article of June 2011
  • Best VB.NET article of May 2011
  • Best VB.NET article of March 2011
  • Best VB.NET article of February 2011
  • Best VB.NET article of January 2011
  • Best VB.NET article of December 2010
  • Best VB.NET article of November 2010

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   
AnswerRe: how to change video's width and height?memberg3rdi27 Sep '12 - 20:48 
I dont think i was to clear in the last message. If you just add a viewbox to the video control "ContentControl1" nothing will work. You need to edit the template of the control and in the template add a viewbox and then play around with the heights and widths to get it just right
AnswerRe: how to change video's width and height?memberg3rdi18 Oct '12 - 21:17 
Ok the 2nd last reply was not to clear either. So 1 last time.
 
IF ANYONE WANTS TO CHANGE THE HEIGHT AND WIDTH
Navigate to "contentControl1" -> right click -> edit copy -> group the control into a viewbox. This is the tricky part => The control has to be larger then the view box in size with the viewbox's size stretch = "Fill" . I found i had to play around with this because the dimensions has to be perfect to prevent black space on either the width or height.
GeneralRe: how to change video's width and height?memberCuervek6 Nov '12 - 23:29 
Can you put code example here??
GeneralRe: how to change video's width and height?memberhocholcito14 Nov '12 - 8:48 
It doesnt work, how do u could make it work?
Regrads
GeneralRe: how to change video's width and height?memberg3rdi14 Nov '12 - 20:29 
hmm.. it works for me. I am not sure if the top level grid has to also be a viewbox which is how I have it in my application. So the whole application is a viewbox, not too sure why that should matter but.
 
 <Style x:Key="ContentControlStyle1" TargetType="{x:Type ContentControl}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ContentControl}">
                        <Viewbox Width="425"
                                 Height="319"
                                 Margin="0"
                                 VerticalAlignment="Stretch"
                                 Stretch="Fill">
                            <ContentPresenter Width="425"
                                              Height="319"
                                              Margin="0"
                                              HorizontalAlignment="Left"
                                              VerticalAlignment="Top" />
                        </Viewbox>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

AnswerRe: how to change video's width and height?memberhocholcito14 Nov '12 - 4:06 
Jorge could you fix the height and the width problem?
Pudiste resolver el problema de la altura y el ancho?
 
Gracias!, THX
Questionmy window i s blackmemberdyma16 Aug '12 - 7:05 
my window is black, but application write files and it is ok
All snapshots is black
 
what' wrongs
 
Dmitry
AnswerRe: my window i s blackmvpMeshack Musundi16 Aug '12 - 9:02 
I haven't experienced this issue. I honestly don't know why that's happening.
"As beings of finite lifespan, our contributions to the sum of human knowledge is one of the greatest endeavors we can undertake and one of the defining characteristics of humanity itself"

GeneralRe: my window i s blackmemberMember 961010721 Nov '12 - 13:01 
have the same problem.. I have installed the latest SDK version and .net4
 
any solution?
GeneralMy vote of 5mvpSergey Alexandrovich Kryukov10 Aug '12 - 12:01 
Nice drawing shown in the camera image. Do you do it?
 
And my 5 for the article, thank you for sharing.
 
—SA

GeneralRe: My vote of 5mvpMeshack Musundi16 Aug '12 - 8:59 
Thanks Sergey.
 
Yes, I'm the one who did the drawing. Smile | :)
"As beings of finite lifespan, our contributions to the sum of human knowledge is one of the greatest endeavors we can undertake and one of the defining characteristics of humanity itself"

QuestionStop Capture is not workingmemberAbhishek136531 Jul '12 - 2:44 
I used the particular code for hosting in Windows Application for Capturing Image and it Worked.But Stop Capture option is not working.I get a error saying "System.AccessViolationException".
AnswerRe: Stop Capture is not workingmvpMeshack Musundi31 Jul '12 - 3:01 
I haven't experienced this issue. I'll look into it.
"As beings of finite lifespan, our contributions to the sum of human knowledge is one of the greatest endeavors we can undertake and one of the defining characteristics of humanity itself"

GeneralRe: Stop Capture is not workingmemberAbhishek13652 Aug '12 - 0:33 
I am trying to do using c# and using windows application.Might be problem with webcamcontrol.dll mostly.
GeneralRe: Stop Capture is not workingmvpMeshack Musundi23 Aug '12 - 23:45 
It should be okay now. I've just updated the code.
"As beings of finite lifespan, our contributions to the sum of human knowledge is one of the greatest endeavors we can undertake and one of the defining characteristics of humanity itself"

GeneralRe: Stop Capture is not workingmemberAbhishek136529 Aug '12 - 20:31 
Thanks it's awesome application....................
Generalfile name of the captured videos after recordingmemberMember 927401929 Jul '12 - 9:06 
hi there,
 
this is a superb code firstly, it works well. but i have only one problem left behind that :
 
i need to change the video and image file names when recording. how to realize this in C# ???
 
thanks...
GeneralRe: file name of the captured videos after recordingmvpMeshack Musundi31 Jul '12 - 2:54 
Member 9274019 wrote:
this is a superb code firstly
Thanks. Smile | :)
Member 9274019 wrote:
i need to change the video and image file names when recording
The control saves the file names using a timestamp to prevent file name conflicts. If you want to change the name you can only do so after encoding is complete.
"As beings of finite lifespan, our contributions to the sum of human knowledge is one of the greatest endeavors we can undertake and one of the defining characteristics of humanity itself"

GeneralRe: file name of the captured videos after recordingmemberMember 927401931 Jul '12 - 12:06 
actually, there are a couple of options that the user can specify saving locations and determining file formats. i think that specifying file names should also be optional through the web cam library. what'd say you ? is it possible for you to update the dll file and put this file name option?? this would be a perfect webcam library for all the users and this improvement should make this code the best among others. if it is not possible for you to realize this update, can you tell me how to overwrite the video files saved before? how can i change file names automatically. because file names are the most important part of my work..
 
thanks for your great and respected effort...
GeneralRe: file name of the captured videos after recordingmvpMeshack Musundi31 Jul '12 - 22:56 
Member 9274019 wrote:
i think that specifying file names should also be optional through the web cam library
I had thought of this while developing the control but the suitability of a timestamp oriented approach overrode that idea. You have to consider that the user may require to capture an image or video immediately without the inconvenience of a dialog box requesting him/her to specify a file-name.
 
Also, leaving the decision of specifying a file-name to the user creates the possibility of file-name conflicts which may lead to deletion of a preexisting file, with the same name. To prevent this you'll have to present the user with more dialogs, informing him/her that a file with that name already exists and asking whether he wants to delete that file. This could be quite inconvenient.
"As beings of finite lifespan, our contributions to the sum of human knowledge is one of the greatest endeavors we can undertake and one of the defining characteristics of humanity itself"

GeneralRe: file name of the captured videos after recordingmemberMember 92740192 Aug '12 - 11:01 
thanks for your concern. i handled the situation. all i needed to do was, to rename the files after being saved. i have written a code segment refresh() to remane the files that begin with "W" since your recorded files were named like "Webcam 01.02.2012 23:50.wmv". refresh finds the files that begin with "W" and renames them as i wanted. i am sharing it so that people can make use of this segment and handle this issue.
 
private void Refresh()
{
string path = vidPath;
string path2 = @"C:\Webcam videos\" + name_you_want;
string searchPattern = "W*";
 
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] files = di.GetFiles(searchPattern, SearchOption.TopDirectoryOnly);

foreach (FileInfo file in files)
{
if(File.Exists(path2))
{
System.IO.File.Delete(path2);
}
file.MoveTo(path2);

}
}
GeneralRe: file name of the captured videos after recordingmvpMeshack Musundi2 Aug '12 - 20:21 
Nice one.Thumbs Up | :thumbsup:
"As beings of finite lifespan, our contributions to the sum of human knowledge is one of the greatest endeavors we can undertake and one of the defining characteristics of humanity itself"

GeneralRemote Streaming Question [modified]memberPaulReis9 Jul '12 - 9:42 
Say I build a windows app that captures a users webcam (video and audio). Can I then stream their webcam (live) to a remote windows encoder server to then publish as a broadcast for people to view? I see in encoder 4 you can connect your webcam and stream it but they (encoder and webcam) have to be on the same machine. I was hoping to build something so I can have a couple remote users stream their webcam to my encoder server to then broadcast as a live event. like ustream and some other services out their. I'd like to build something basic myself.

modified 9 Jul '12 - 18:36.

GeneralRe: Remote Streaming QuestionmvpMeshack Musundi10 Jul '12 - 21:05 
PaulReis wrote:
Can I then stream their webcam (live) to a remote windows encoder server to then publish as a broadcast for people to view?
Yes, it is possible to do so. Your users would have your Windows app and the Expression Encoder SDK, which your app utilizes, installed on their machines. They would then stream to your server and you can broadcast it from there.
"As beings of finite lifespan, our contributions to the sum of human knowledge is one of the greatest endeavors we can undertake and one of the defining characteristics of humanity itself"

QuestionHow to change the camera resolution?memberdennyimanuel9 Jul '12 - 1:44 
I wonder how are we going to change the camera properties? Like resolution, brightness, color saturation, etc.?
AnswerRe: How to change the camera resolution?mvpMeshack Musundi10 Jul '12 - 21:07 
Hi,
 
The Expression Encoder SDK doesn't support such tasks for live encoding.
"As beings of finite lifespan, our contributions to the sum of human knowledge is one of the greatest endeavors we can undertake and one of the defining characteristics of humanity itself"

BugProblem with other that other camera than "Screen capture source"membersprixxx4 Jul '12 - 9:44 
Hi
I download your app in C#(WPF) include dll's.
If i start app and switch camera to my laptop(ASUS K50in 1,3Mpix).I capture camera and i see:
 
"Project: WPF Webcam, stop working"
 
in the past when i don't change check:
Enable unmanaged code debugging
Enable SQL server debugging
 
i was seen:
"vshost32.exe has stopped working"
 
Someone know what i should do to repair app in my pc.?
ps. Sorry for my english
GeneralRe: Problem with other that other camera than "Screen capture source"mvpMeshack Musundi4 Jul '12 - 21:05 
Have you installed the Expression Encoder SDK?
GeneralRe: Problem with other that other camera than "Screen capture source"membersprixxx4 Jul '12 - 23:43 
yes i install SDK from article " windows encoder expression..."
 
i check bug in other app and i see that when i use another camer that screen, i have crash
 
ps. i have 1-3s screen in my camera and crash
GeneralRe: Problem with other that other camera than "Screen capture source"mvpMeshack Musundi8 Jul '12 - 20:59 
I'm trying to get this. You downloaded the C# project, ran it and experienced an error when switching cameras?
GeneralRe: Problem with other that other camera than "Screen capture source"membersprixxx9 Jul '12 - 14:54 
Yes i don't change anything in your project.
I use Visual Studio 2012 ultimate, 1,3 Mpix camera in Asus(instal windows encoder i don't se any bugs in "errors".
 
hmm i use screen capture and ok. I switch to my notebook camera 1s i see video and crash
GeneralRe: Problem with other that other camera than "Screen capture source"mvpMeshack Musundi10 Jul '12 - 21:08 
I haven't experienced this issue. Don't know why that's happening. D'Oh! | :doh:
"As beings of finite lifespan, our contributions to the sum of human knowledge is one of the greatest endeavors we can undertake and one of the defining characteristics of humanity itself"

QuestionRecord Multiple Cameras?memberTKCA26 Jun '12 - 15:38 
Hi there!
 
Let me begin by saying that this looks awesome! Thumbs Up | :thumbsup: I was looking for a tutorial for a project similar to this.
 
my question is, would it be possible to use multiple cameras with this? (don't have a lot of experience with .NET framework)
 
Appreciate any reply.
AnswerRe: Record Multiple Cameras?mvpMeshack Musundi26 Jun '12 - 22:38 
Hi,
 
If you have several webcams connected to your PC then you can use Expression Encoder's FindDevices() method to locate those webcams, and their details. From there you can list the devices in a ListBox or ComboBox.
' Find available a/v devices.
Private Sub FindDevices()
    Dim vidDevices = EncoderDevices.FindDevices(EncoderDeviceType.Video)
    Dim audDevices = EncoderDevices.FindDevices(EncoderDeviceType.Audio)
 
    For Each dvc In vidDevices
        VidDvcsComboBox.Items.Add(dvc.Name)
    Next
 
    For Each dvc In audDevices
        AudDvcsComboBox.Items.Add(dvc.Name)
    Next
End Sub
You could also opt to use data binding to do this but since you're not very conversant with .NET I won't delve into that.
 
After you have your list control showing the names of available devices you can simply just change to the camera you wish the control to display. This can be done by simply setting the Webcam Control's VideoDevice property.
webcamCtrl.VideoDevice = VidDvcComboBox.SelectedValue
Element binding can also be of great assistance here as an alternative approach.
 
I hope my reply will be of some assistance.
GeneralRe: Record Multiple Cameras?memberTKCA27 Jun '12 - 4:15 
Thanks for the quick reply,Meshack.
 
I'll definitely look into data binding. Based on what you implied, it sounds a better approach to this.
 
Since you are the expert here, correct me if I'm wrong but if I want to capture simultaneously, say 3 cameras,I would get into multithreading. right?
 
Again, Appreciate the help!Thumbs Up | :thumbsup:
GeneralRe: Record Multiple Cameras?mvpMeshack Musundi27 Jun '12 - 5:36 
No, that isn't a multithreading scenario. A Webcam control can only display video from one camera. In a 3 camera scenario what you need is to have 3 Webcam controls and set the VideoDevice property of each control to a particular camera. Smile | :)
GeneralRe: Record Multiple Cameras?memberTKCA27 Jun '12 - 9:18 
Thank you,
 
My project is about using multiple cameras simultaneosly, that's why I ask.
 
Appreciate the help, you the best Thumbs Up | :thumbsup:
QuestionSave image every framememberrejectkosta11 Jun '12 - 9:25 
First of all, this is great!!! Smile | :)
I have two questions:
1. Is it possible (and if it is how?) to Take Snapshot every webcam frame? (Is there some event like new frame arrived or something?). I need to take take snapshot every webcam frame and save it into buffer.
2. How to get webcam frame rate?
 
Thanks in advance!!!
AnswerRe: Save image every framemvpMeshack Musundi11 Jun '12 - 21:24 
Hi,
rejectkosta wrote:
Is it possible (and if it is how?) to Take Snapshot every webcam frame? (Is there some event like new frame arrived or something?). I need to take take snapshot every webcam frame and save it into buffer.
Currently it isn't possible to take a snapshot of every webcam frame and there aren't any events to aid this. Frown | :(
 
rejectkosta wrote:
How to get webcam frame rate?
There isn't currently a property that provides this info if you are streaming from the webcam. The LiveDeviceSource class doesn't have such a property, unlike the LiveFileSource class which has a FrameRate property.
QuestionCan you stream this capture?membermagic.on7 Jun '12 - 6:36 
You said you can save the file in mp4 ... can it be stream after beeing encoded?
 
Realy need a hint on how to stream my webcam to android (h.264 format)
AnswerRe: Can you stream this capture?mvpMeshack Musundi7 Jun '12 - 21:45 
Hi,
 
Yes, it is possible to stream after encoding;

VB.NET

Using job As New LiveJob
    Dim fileSource As LiveFileSource = job.AddFileSource("C:\VideoClips\MyVid.mp4")
 
    job.ApplyPreset(LivePresets.H264IISSmoothStreaming480pStandard)
    job.ActivateSource(fileSource)
 
    Dim format As New PullBroadcastPublishFormat
    format.BroadcastPort = 8080
 
    job.PublishFormats.Add(format)
 
    job.StartEncoding()
End Using

C#

Using  (LiveJob job = new LiveJob())
{
    LiveFileSource fileSource = job.AddFileSource(@"C:\VideoClips\MyVid.mp4");
 
    job.ApplyPreset(LivePresets.H264IISSmoothStreaming480pStandard);
    job.ActivateSource(fileSource);
 
    PullBroadcastPublishFormat format = new PullBroadcastPublishFormat;
    format.BroadcastPort = 8080;
 
    job.PublishFormats.Add(format);
 
    job.StartEncoding();
}
The code above sends the file to a local port.
 
You could optionally just stream directly from the webcam;

VB.NET

Using job As New LiveJob
    Dim deviceSource As LiveDeviceSource = job.AddDeviceSource(vidDevice, audioDevice)
 
    job.ApplyPreset(LivePresets.H264IISSmoothStreaming480pStandard)
    job.ActivateSource(deviceSource)
 
    Dim format As New PullBroadcastPublishFormat
    format.BroadcastPort = 8080
 
    job.PublishFormats.Add(format)
 
    job.StartEncoding()
End Using

C#

Using  (LiveJob job = new LiveJob())
{
    LiveDeviceSource deviceSource = job.AddDeviceSource(vidDevice, audioDevice);
 
    job.ApplyPreset(LivePresets.H264IISSmoothStreaming480pStandard);
    job.ActivateSource(deviceSource);
 
    PullBroadcastPublishFormat format = new PullBroadcastPublishFormat;
    format.BroadcastPort = 8080;
 
    job.PublishFormats.Add(format);
 
    job.StartEncoding();
}
magic.on wrote:
Realy need a hint on how to stream my webcam to android (h.264 format)

If you connect your Android device to your PC/laptop, using a USB cable, you can just stream the webcam video to your Android device's Videos directory;

VB.NET

Using job As New LiveJob
    Dim deviceSource As LiveDeviceSource = job.AddDeviceSource(vidDevice, audioDevice)
 
    job.ApplyPreset(LivePresets.H264IISSmoothStreaming480pStandard)
    job.ActivateSource(deviceSource)
 
    Dim dir As String = "...\Videos\MyVid.mp4"
 
    Dim format As New FileArchivePublishFormat(dir)
   
    job.PublishFormats.Add(format)
 
    job.StartEncoding()
End Using

C#

Using  (LiveJob job = new LiveJob())
{
    LiveDeviceSource deviceSource = job.AddDeviceSource(vidDevice, audioDevice);
 
    job.ApplyPreset(LivePresets.H264IISSmoothStreaming480pStandard);
    job.ActivateSource(deviceSource);
 
    String dir = @"...\Videos\MyVid.mp4";    
 
    FileArchivePublishFormat format = new FileArchivePublishFormat(dir);
  
    job.PublishFormats.Add(format);
 
    job.StartEncoding();
}

QuestionAwesomemembertarjeetsalh3 Jun '12 - 22:42 
Awesome Code ..Thankyou
AnswerRe: AwesomemvpMeshack Musundi4 Jun '12 - 1:42 
Thanks. I'm glad you like it. Smile | :)
QuestionSecond Problem with the snapshot methodmemberSam Michael26 May '12 - 11:13 
If you have more than one monitor and move the program to a second monitor, the image in the window shows the original area in the first monitor. There has to be a better way to do this. I have been playing with with the following code to no avail. Perhaps it will spark some ideas however:
 
Dim v As Runtime.InteropServices.HandleRef
v = deviceSource.PreviewWindow.ChildWindow
 
Dim gr As Graphics = Graphics.FromHwnd(v)
gr.DrawImage(bmap0, r)
Picturebox1.Image = bmap0
 
I get no errors but no image is displayed either. If I had to guess, I would say that the image is not in the childwindow of the previewwindow - so where is it? Who owns it?
 
For what it is worth, doing the following doesn't work:
WebCamPanel.DrawToBitMap (where WebCamPanel is my preview window) also doesn't work. It simply returns a blank screen (I would guess that it contains to image and that a different panel now resides in it.)
 
This is what frustrates me about Microsoft. The learning curve on all this stuff is horrific.
 
That said, thank you Meshack for your effort. You have me much closer.
 
Sam
AnswerRe: Second Problem with the snapshot methodmvpMeshack Musundi27 May '12 - 20:22 
Hi Sam,
 
I had attempted the approaches you mention and also got the same results. The approach that the control currently uses is the only one I managed to get results with.
 
This issue currently doesn't have a more elegant approach since the Expression Encoder SDK doesn't contain the means to take a snapshot of live video. This issue has come up several times in the Expression Encoder blog forums; http://social.expression.microsoft.com/Forums/eu/encoder/thread/f9e4b70e-9479-4c16-a721-2f31a0100a37
GeneralRe: Second Problem with the snapshot methodmemberSam Michael29 May '12 - 14:14 
For what it's worth, I added a few comments in that same thread. After several days of chasing my tail, I have convince myself that EE4 is incapable of this task. Outside of simple streaming and encoding, there is no good way of getting a single image and certainly not in a reasonable amount of time. My test of the current snapshot function is that it takes between 17 and 30 ms to execute on average (which, for me, is disastrous).
 
You are the first Kenyan programmer that I have ever had a dialog with. Thank you for sharing your work. How is the weather in Kenya?
 
Sam
GeneralRe: Second Problem with the snapshot methodmvpMeshack Musundi29 May '12 - 20:01 
Hi Sam,
 
Its been raining but the weather today is bright and sunny. Smile | :)
QuestionSnap shot Method is painfully slow.memberSam Michael26 May '12 - 8:20 
I have run into this problem before but copies from the copy from screen function are beyond painfully slow. I am getting somewhere between 11 and 30 ms for the operation. I have never been sure as to why this is the case, but unfortunately, it's true.
 
Does anyone have any idea if there is a way of getting the image in a faster way. I am writing an application that is streaming the images to a database and I need to stay in sync. Ideally, the image is already available somewhere in the encoder SDK somewhere and accessing it directly as opposed to doing a screen copy would be far more preferable. Any ideas would be appreciated.
 
Thanks,
 
Sam
QuestionHey That webcamcontrol.dll reference error...........................memberAbhishek136523 May '12 - 23:23 
Trying to stop the webcam found an error could u help on that...........................................error says
 

 
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
AnswerRe: Hey That webcamcontrol.dll reference error...........................mvpMeshack Musundi24 May '12 - 1:48 
Hi Abhishek,
 
I don't know what could be the issue there. I haven't experienced the problem you've mentioned. I'll look into it but in the meantime try finding out exactly what the cause is.
 
Thanks

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 11 Feb 2013
Article Copyright 2011 by Meshack Musundi
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid