2011-08-08 34 views
5

Estoy tratando de grabar audio en C# usando NAudio. Después de mirar la Demostración de NAudio Chat, utilicé un código de allí para grabar.Grabación con NAudio usando C#

Aquí está el código:

using System; 
using NAudio.Wave; 

public class FOO 
{ 
    static WaveIn s_WaveIn; 

    static void Main(string[] args) 
    { 
     init(); 
     while (true) /* Yeah, this is bad, but just for testing.... */ 
      System.Threading.Thread.Sleep(3000); 
    } 

    public static void init() 
    { 
     s_WaveIn = new WaveIn(); 
     s_WaveIn.WaveFormat = new WaveFormat(44100, 2); 

     s_WaveIn.BufferMilliseconds = 1000; 
     s_WaveIn.DataAvailable += new EventHandler<WaveInEventArgs>(SendCaptureSamples); 
     s_WaveIn.StartRecording(); 
    } 

    static void SendCaptureSamples(object sender, WaveInEventArgs e) 
    { 
     Console.WriteLine("Bytes recorded: {0}", e.BytesRecorded); 
    } 
} 

Sin embargo, el manejador de sucesos no se está llamando. Estoy utilizando la versión .NET 'v2.0.50727' y compilar como:

csc file_name.cs /reference:Naudio.dll /platform:x86 

Respuesta

5

Si este es todo el código, a continuación, se echa en falta un message loop. Todos los eventos específicos de eventHandler requieren un bucle de mensaje. Puede agregar una referencia a Application o Form según su necesidad.

Aquí hay un ejemplo usando Form:

using System; 
using System.Windows.Forms; 
using System.Threading; 
using NAudio.Wave; 

public class FOO 
{ 
    static WaveIn s_WaveIn; 

    [STAThread] 
    static void Main(string[] args) 
    { 
     Thread thread = new Thread(delegate() { 
      init(); 
      Application.Run(); 
     }); 

     thread.Start(); 

     Application.Run(); 
    } 

    public static void init() 
    { 
     s_WaveIn = new WaveIn(); 
     s_WaveIn.WaveFormat = new WaveFormat(44100, 2); 

     s_WaveIn.BufferMilliseconds = 1000; 
     s_WaveIn.DataAvailable += new EventHandler<WaveInEventArgs>(SendCaptureSamples); 
     s_WaveIn.StartRecording(); 
    } 

    static void SendCaptureSamples(object sender, WaveInEventArgs e) 
    { 
     Console.WriteLine("Bytes recorded: {0}", e.BytesRecorded); 
    } 
} 
+3

Sí, la falta de bucle de mensajes es el problema. Una solución alternativa es usar devoluciones de llamada de funciones. –

+0

¿Podemos convertir el formato para guardarlo como MP3? – 7addan

Cuestiones relacionadas