使用 C# 使用 NAudio 进行录音
我正在尝试使用 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);
}
}
但是,事件处理程序没有被调用。我正在使用 .NET 版本“v2.0.50727”并将其编译为:
csc file_name.cs /reference:Naudio.dll /platform:x86
I am trying to record audio in C# using NAudio. After looking at the NAudio Chat Demo, I used some code from there to record.
Here is the code:
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);
}
}
However, the eventHandler is not being called. I am using .NET version 'v2.0.50727' and compiling it as:
csc file_name.cs /reference:Naudio.dll /platform:x86
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果这是您的整个代码,那么您就缺少
消息循环
。所有 eventHandler 特定事件都需要消息循环。您可以根据需要添加对Application
或Form
的引用。以下是使用
Form
的示例:If this is your whole code, then you are missing a
message loop
. All the eventHandler specific events requires a message loop. You can add a reference toApplication
orForm
as per your need.Here is an example by using
Form
:只需使用
WaveInEvent
而不是WaveIn
即可运行代码。然后处理发生在单独的线程上,而不是在窗口消息循环中,这在控制台应用程序中不可用。延伸阅读:
https://github.com/naudio/NAudio/ wiki/Understanding-Output-Devices#waveout-and-waveoutevent
(该功能已添加 2012,所以在提出问题时它不可用)
Just use
WaveInEvent
instead ofWaveIn
and the code will work. Then the handling happens on a separate thread instead of in a window message loop, which isn't available in a console application.Further reading:
https://github.com/naudio/NAudio/wiki/Understanding-Output-Devices#waveout-and-waveoutevent
(The feature was added in 2012, so at the time of the question it wasn't available)