我正在尝试在 C# 中使用 NAudio 录制语音,但我被困在两个地方:
1. A crash:
通过THIS SO page 中稍微修改的代码形式,我得到了一个NullReferenceException
. 这是崩溃日志:
************** Exception Text **************
System.NullReferenceException: Object reference not set to an instance of an object.
at NAudio.Wave.WaveIn.Callback(IntPtr waveInHandle, WaveMessage message, IntPtr userData, WaveHeader waveHeader, IntPtr reserved)
at NAudio.Wave.WaveWindow.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
代码是:
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)
{
init();
Application.Run();
}
public static void record()
{
while (true)
{
Console.WriteLine("Hit Enter to START Recording.\n");
Console.ReadLine();
s_WaveIn.StartRecording();
Console.WriteLine("Hit Enter to STOP recording.\n");
Console.ReadLine();
s_WaveIn.StopRecording();
}
}
public static void DeviceInit(int rate, int channels)
{
s_WaveIn = new WaveIn();
s_WaveIn.WaveFormat = new WaveFormat(rate, channels);
s_WaveIn.BufferMilliseconds = 1000;
s_WaveIn.DataAvailable += new EventHandler<WaveInEventArgs>(SendCaptureSamples);
}
public static void init()
{
DeviceInit(44100, 2);
Thread t1 = new Thread(delegate() {
record();
});
t1.Start();
}
static void SendCaptureSamples(object sender, WaveInEventArgs e)
{
Console.WriteLine("Bytes recorded: {0}", e.BytesRecorded);
}
}
大多数情况下,这发生在我开始第三次录制时。知道是什么原因造成的吗?
*2. Modifying rate and channels at runtime.*
在我的实际代码中,我s_WaveIn.WaveFormat = new WaveFormat(new_rate, new_channels);
在调用之前使用重置波形格式StartRecording()
。我没有打电话Dispose()
,因为这需要重置DataAvailable
回调,为此,我需要另一个消息循环。这种方法是否正确,或者我应该先调用 Dispose,然后用新格式重新初始化 s_WaveIn?
谢谢你。