【发布时间】:2014-05-17 15:32:04
【问题描述】:
【问题讨论】:
-
为什么不呢?你试过什么?
-
它是一个 audio 库,它不关心用户界面。你唯一能犯的错误就是不去尝试。
【问题讨论】:
是的,这是可能的。
您必须将代码拆分为两个按钮,例如 start 和 stop。Console.ReadKey() 之前的代码进入 start 按钮的 Click 事件,Console.ReadKey() 之后的所有代码进入 stop 按钮的 click 事件。
在控制台变体中,所有变量都是方法的本地变量。在不再起作用的 WinForms 变体中,我们将局部变量提升到窗体的类级别。
using 语句基本上是一个 try/catch/finally 块,在 finally 块中调用 Dispose。关闭和处理现在成为我们自己的责任,因此在 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;
}
}
}
以上代码由用户thefiloe改编自this answer
【讨论】: