2011-08-08 17 views
5

Próbuję nagrać dźwięk w języku C# za pomocą NAudio. Po obejrzeniu Demo na czacie NAudio, użyłem stamtąd kodu do nagrania.Nagrywanie w NAudio przy użyciu C#

Oto kod:

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); 
    } 
} 

Jednak Podprogram nie jest wywoływana. Używam wersji .NET „v2.0.50727” i kompilowanie go jako:

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

Odpowiedz

5

Jeśli jest to cały kod, to brakuje message loop. Wszystkie zdarzenia określone przez eventHandler wymagają pętli komunikatów. Możesz dodać odniesienie do Application lub Form według potrzeb.

Oto przykład za pomocą 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

Tak, brak pętli komunikatów jest problem. Alternatywną poprawką jest użycie wywołań funkcji. –

+0

Czy możemy przekonwertować format, aby zapisać go jako MP3! – 7addan