2011-02-10 20 views
14

Necesito capturar video desde una cámara web. ¿Hay alguna clase en C# /. NET que me pueda ayudar con esto? Solo me interesan los datos en tiempo real.¿Cómo capturo video desde una cámara web?

¿Y hay buenos libros de C#/.NET que pueda estudiar para obtener un conocimiento profundo del idioma y la plataforma?

+0

Bienvenido a StackOverflow. Te recomiendo que te registres para obtener una cuenta para que puedas hacer un seguimiento de tus preguntas constantemente. Esta es una excelente pregunta, pero usted hace dos preguntas aquí. ¿Puedes hacer que la segunda pregunta sea una nueva pregunta? Creo que en realidad puede encontrar la respuesta que desea aquí: [La guía y la lista definitiva de C++ Book] (http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) pero No dudaría en preguntar si eso no puede ayudarte. Debería ser capaz de hacerlo. – jcolebrand

+1

Le recomendaría que dividiera sus preguntas en dos partes: la parte de la cámara web y la parte de libros. –

+1

@drachenstern: Duda que encuentre la respuesta a su pregunta sobre C# en un libro sobre C++. Supongo que es posible, sin embargo. –

Respuesta

12

Esto es lo que uso. Es necesario una primera clase para recorrer sus dispositivos:

public class DeviceManager 
{ 
    [DllImport("avicap32.dll")] 
    protected static extern bool capGetDriverDescriptionA(short wDriverIndex, 
     [MarshalAs(UnmanagedType.VBByRefStr)]ref String lpszName, 
     int cbName, [MarshalAs(UnmanagedType.VBByRefStr)] ref String lpszVer, int cbVer); 

    static ArrayList devices = new ArrayList(); 

    public static TCamDevice[] GetAllDevices() 
    { 
     String dName = "".PadRight(100); 
     String dVersion = "".PadRight(100); 

     for (short i = 0; i < 10; i++) 
     { 
      if (capGetDriverDescriptionA(i, ref dName, 100, ref dVersion, 100)) 
      { 
       TCamDevice d = new TCamDevice(i); 
       d.Name = dName.Trim(); 
       d.Version = dVersion.Trim(); 

       devices.Add(d); 
      } 
     } 

     return (TCamDevice[])devices.ToArray(typeof(TCamDevice)); 
    } 

    public static TCamDevice GetDevice(int deviceIndex) 
    { 
     return (TCamDevice)devices[deviceIndex]; 
    } 
} 

y éste para controlar la leva.

public class TCamDevice 
{ 
    private const short WM_CAP = 0x400; 
    private const int WM_CAP_DRIVER_CONNECT = 0x40a; 
    private const int WM_CAP_DRIVER_DISCONNECT = 0x40b; 
    private const int WM_CAP_EDIT_COPY = 0x41e; 
    private const int WM_CAP_SET_PREVIEW = 0x432; 
    private const int WM_CAP_SET_OVERLAY = 0x433; 
    private const int WM_CAP_SET_PREVIEWRATE = 0x434; 
    private const int WM_CAP_SET_SCALE = 0x435; 
    private const int WS_CHILD = 0x40000000; 
    private const int WS_VISIBLE = 0x10000000; 

    [DllImport("avicap32.dll")] 
    protected static extern int capCreateCaptureWindowA([MarshalAs(UnmanagedType.VBByRefStr)] ref string lpszWindowName, 
     int dwStyle, int x, int y, int nWidth, int nHeight, int hWndParent, int nID); 

    [DllImport("user32", EntryPoint = "SendMessageA")] 
    protected static extern int SendMessage(int hwnd, int wMsg, int wParam, [MarshalAs(UnmanagedType.AsAny)] object lParam); 

    [DllImport("user32")] 
    protected static extern int SetWindowPos(int hwnd, int hWndInsertAfter, int x, int y, int cx, int cy, int wFlags); 

    [DllImport("user32")] 
    protected static extern bool DestroyWindow(int hwnd); 

    int index; 
    int deviceHandle; 

    public TCamDevice(int index) 
    { 
     this.index = index; 
    } 

    private string _name; 

    public string Name 
    { 
     get { return _name; } 
     set { _name = value; } 
    } 

    private string _version; 

    public string Version 
    { 
     get { return _version; } 
     set { _version = value; } 
    } 

    public override string ToString() 
    { 
     return this.Name; 
    } 
    /// <summary> 
    /// To Initialize the device 
    /// </summary> 
    /// <param name="windowHeight">Height of the Window</param> 
    /// <param name="windowWidth">Width of the Window</param> 
    /// <param name="handle">The Control Handle to attach the device</param> 
    public void Init(int windowHeight, int windowWidth, int handle) 
    { 
     string deviceIndex = Convert.ToString(this.index); 
     deviceHandle = capCreateCaptureWindowA(ref deviceIndex, WS_VISIBLE | WS_CHILD, 0, 0, windowWidth, windowHeight, handle, 0); 

     if (SendMessage(deviceHandle, WM_CAP_DRIVER_CONNECT, this.index, 0) > 0) 
     { 
      SendMessage(deviceHandle, WM_CAP_SET_SCALE, -1, 0); 
      SendMessage(deviceHandle, WM_CAP_SET_PREVIEWRATE, 0x42, 0); 
      SendMessage(deviceHandle, WM_CAP_SET_PREVIEW, -1, 0); 

      SetWindowPos(deviceHandle, 1, 0, 0, windowWidth, windowHeight, 6); 
     } 
    } 

    /// <summary> 
    /// Shows the webcam preview in the control 
    /// </summary> 
    /// <param name="windowsControl">Control to attach the webcam preview</param> 
    public void ShowWindow(global::System.Windows.Forms.Control windowsControl) 
    { 
     Init(windowsControl.Height, windowsControl.Width, windowsControl.Handle.ToInt32());       
    } 

    /// <summary> 
    /// Stop the webcam and destroy the handle 
    /// </summary> 
    public void Stop() 
    { 
     SendMessage(deviceHandle, WM_CAP_DRIVER_DISCONNECT, this.index, 0); 

     DestroyWindow(deviceHandle); 
    } 
} 

El ShowWindow toma su PictureBox como parámetro.

+0

estoy usando la misma manera que lo hace, pero encontré que la cámara web no se invoca siempre. si reinicio mi sistema, la cámara web invocará cuando presione el botón de inicio, pero si paro y de nuevo presiono iniciar, el video no se muestra. los valores de SendMessage (deviceHandle, WM_CAP_DRIVER_CONNECT, this.index, 0 son cero y no se muestra ningún video). Alguien me sugirió que cambiara el valor de handle/this.index cada vez, pero esto tampoco funcionó. – Swati

+0

tampoco pude encuentre cómo guardar este video obtenido en formato mp4. Por favor, ayuda – Swati

+0

Luego trato de llamar a DeviceManager.GetAllDevices() arroja "System.EntryPointNotFoundException:" Не удается найти точку входа "CapGetDriverDescriptionA" в DLL "avicap32.dll". "" ¿Qué hago incorrecto? – EgoPingvina

4

Le recomendaría que use la biblioteca de terceros. Sería la mejor solución en lugar de inventar su propia bicicleta. Aquí, utilicé AForge.Net. Aunque tiene algunos problemas con respecto al rendimiento, yo también modifiqué la biblioteca cuando el rendimiento se convirtió en un problema crítico para mí. El código de AForge.Net es de código abierto y puede modificarlo según sus necesidades.

En cuanto a los libros, definitivamente debe mirar Jeffrey Richter's "CLR via C#" y John Skeet's "C# in Depth".

-1

Use WebCam_Capture.dll para capturar Fotos y videos. Aquí está Link aquí está el código fuente para ese LINK

Cuestiones relacionadas