I'm trying to record audio, and I don't want to simply use the System.Threading.Thread.Sleep(x)
function because I want to control the recording myself. Here's what I have..
private void buttonStart_Click(object sender, EventArgs f)
{
using (WasapiCapture capture = new CSCore.SoundIn.WasapiLoopbackCapture())
{
//initialize the selected device for recording
capture.Initialize();
//... stuff...
//create a wavewriter to write the data to
using (WaveWriter w = new WaveWriter(@directory, capture.WaveFormat))
{
capture.DataAvailable += (s, e) =>
{
//save the recorded audio
w.Write(e.Data, e.Offset, e.ByteCount);
};
//start recording
capture.Start();
//wait until button is pressed again...
//stop recording
capture.Stop();
}
}
}
I want to make it so that when I click buttonStart
again, the capture.Stop();
line will run. I'm pretty new to C#, so I just wanted to ask.
WasapiCapture capture;
private void buttonStart_Click(object sender, EventArgs f)
{
if(capture == null)
capture = new new CSCore.SoundIn.WasapiLoopbackCapture();
capture.Initialize();
capture.DataAvailable += (s, e) =>
{
//save the recorded audio
using (WaveWriter w = new WaveWriter(@directory, capture.WaveFormat))
{
w.Write(e.Data, e.Offset, e.ByteCount);
}
};
//start recording
capture.Start();
}
else {
//stop recording
capture.Stop();
capture = null;
}
}
}
To let some code wait until... you can use threads. And once of best ways of implementing a wait until some event occurs is using an AutoResetEvent
:
public class Program
{
// AutoResetEvent constructor argument is if the event should be start
// signaled or not.
//
// A ResetEvent is like a door. If it's signaled, the door is open,
// and if it's not signaled, the door is closed.
private static readonly AutoResetEvent ResetEvent = new AutoResetEvent(false);
public static void Main()
{
Task.Run
(
() =>
{
Thread.Sleep(3000);
// Calling Set() is signaling the event. That is,
// you open the door. And other threads waiting until
// the door is opened get resumed.
ResetEvent.Set();
}
);
// Since the ResetEvent isn't signaled, the door is closed
// and it'll wait until the door gets opened (i.e. the event
// gets signaled).
ResetEvent.WaitOne();
Console.WriteLine("This will be written once the ResetEvent has been signaled in the other thread");
}
}
Now you can apply this approach to yours and you'll get exactly what you are asking for.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.