我正在开发一个控制台应用程序,其中编写了两个方法start
和stop
。当调用start
方法时,它开始从系统捕获音频数据并保持工作状态,并且控制台卡在一个点上。现在我想调用stop
方法来停止start
方法,但是控制台仍然停留在start
方法上。我尝试从另一个控制台调用stop方法,但它失败了:“未处理的异常:System.NullReferenceException:对象引用未设置为对象的实例。”
我怎么能做到这一点?
首先,我想打电话给wavtomp3
,当我正在工作时,我想从控制台应用调用stoprecording()
。
这是我的代码:
static LameMP3FileWriter wri;
static IWaveIn waveIn;
public void wavtomp3(string fName,string storageLocation)
{
string[] aFileName=fName.Split('.');
aFileName[0] = aFileName[0] + ".mp3";
string aSaveLocation = storageLocation + "\\"+aFileName[0];
// MessageBox.Show("Sample Rate=" + waveIn.WaveFormat.SampleRate.ToString());
// string fname = DateTime.Now.Ticks.ToString();
// Start recording from loopback
waveIn = new WasapiLoopbackCapture();
wri = new LameMP3FileWriter(aSaveLocation, waveIn.WaveFormat, 44);
waveIn.DataAvailable += waveIn_DataAvailable;
waveIn.RecordingStopped += waveIn_RecordingStopped;
waveIn.StartRecording();
}
static void waveIn_RecordingStopped(object sender, StoppedEventArgs e)
{
if (waveIn != null) // working around problem with double raising of RecordingStopped
{
waveIn.Dispose();
waveIn = null;
}
if (wri != null)
{
wri.Close();
wri = null;
}
}
static void waveIn_DataAvailable(object sender, WaveInEventArgs e)
{
if (wri != null)
if (e.BytesRecorded == 0)
{
wri.Write(e.Buffer, 0, 12800);
Debug.WriteLine("Adding Silence To File No Sound is playing");
}
else if (e.BytesRecorded > 0)
{
wri.Write(e.Buffer, 0, e.BytesRecorded);
Debug.WriteLine("Sound Playing From Sound Card and recording");
}
Debug.WriteLine("bytes record=" + e.BytesRecorded);
}
public void stoprecording()
{
waveIn.StopRecording();
Debug.WriteLine("StopRecording");
}