我正在尝试使用NAudio在C#中录制音频。看完NAudio Chat Demo后,我用了一些代码来记录。
以下是代码:
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);
}
}
但是,没有调用eventHandler。我正在使用.NET版本'v2.0.50727'并将其编译为:
csc file_name.cs /reference:Naudio.dll /platform:x86
答案 0 :(得分:5)
如果这是您的整个代码,那么您错过了message loop
。所有eventHandler特定事件都需要消息循环。您可以根据需要添加对Application
或Form
的引用。
以下是使用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);
}
}
答案 1 :(得分:0)
只需使用WaveInEvent
代替WaveIn
,代码即可使用。然后处理发生在一个单独的线程而不是窗口消息循环中,这在控制台应用程序中是不可用的。
进一步阅读:
https://github.com/naudio/NAudio/wiki/Understanding-Output-Devices#waveout-and-waveoutevent
(该功能已添加in 2012,因此在问题发布时无法使用此功能)