发布于 2014-04-05 09:00:58
是的,这是可能的。
您必须将代码拆分为两个按钮,比如start和stop。
Console.ReadKey()之前的代码进入start按钮的Click事件,Console.ReadKey()之后的所有内容都进入stop按钮的单击事件。
在控制台变量中,所有变量都是该方法的本地变量。在不再工作的WinForms变量中,我们将局部变量提升到表单的类级别。
using语句基本上是try/catch/finally块,调用在finally块中释放。关闭和处理现在成为我们自己的责任,因此在stop中,调用Writer和Capture的Dispose方法,然后为类变量分配一个空值。
你最后的下场是这样的:
public class Form1:Form
{
// other stuff
private WasapiCapture capture = null;
private WaveWriter w = null;
private void start_Click(object sender, EventArgs e)
{
capture = new WasapiLoopbackCapture();
capture.Initialize();
//create a wavewriter to write the data to
w = new WaveWriter("dump.wav", capture.WaveFormat));
//setup an eventhandler to receive the recorded data
capture.DataAvailable += (s, capData) =>
{
//save the recorded audio
w.Write(capData.Data, capData.Offset, capData.ByteCount);
};
//start recording
capture.Start();
}
private void stop_Click(object sender, EventArgs e)
{
if (w != null && capture !=null)
{
//stop recording
capture.Stop();
w.Dispose();
w = null;
capture.Dispose();
capture = null;
}
}
}以上代码由用户this answer thefiloe改编而来。
https://stackoverflow.com/questions/22877709
复制相似问题