[英]Recording with NAudio using C#
我正在嘗試使用NAudio在C#中錄制音頻。 看完NAudio Chat演示之后,我從那里使用了一些代碼進行記錄。
這是代碼:
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
如果這是您的全部代碼,則您缺少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);
}
}
只需使用WaveInEvent
而不是WaveIn
,代碼就可以工作。 然后,將在單獨的線程上而不是在窗口消息循環中進行處理,而在控制台應用程序中則不存在。
進一步閱讀:
https://github.com/naudio/NAudio/wiki/Understanding-Output-Devices#waveout-and-waveoutevent
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.