I am recording voice from my windows application on time intervals. I made a class to start and stop the voice recording and calling its function on my form.
The class is as follows
class VoiceRecording {
[DllImport("winmm.dll", EntryPoint = "mciSendStringA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern int mciSendString(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback);
public VoiceRecording() {
}
public void StartRecording() {
mciSendString("open new Type waveaudio Alias recsound", "", 0, 0);
mciSendString("record recsound", "", 0, 0);
}
public void StopRecording(int FileNameCounter) {
mciSendString(String.Format("save recsound {0}", @"E:\WAVFiles\" + FileNameCounter + ".wav"), "", 0, 0);
mciSendString("close recsound ", "", 0, 0);
Computer c = new Computer();
c.Audio.Stop();
}
}
Now when I call these functions on button click event like
int FileNameCounter = 1;
private void btnStart_Click(object sender, EventArgs e) {
VR = new VoiceRecording();
VR.StartRecording();
}
private void btnStop_Click(object sender, EventArgs e) {
VR.StopRecording(FileNameCounter++);
VR = null;
}
everything goes fine, no matter how slow or fast I click the buttons, the code always create numbered files.
I put the code into a loop as well like
for (int i = 0; i < 10; i++) {
VR = new VoiceRecording();
VR.StartRecording();
VR.StopRecording(FileNameCounter++);
VR = null;
}
it also runs well and creates 10 numbered files.
Till now everything is fine, and here I introduced Timer like this
System.Timers.Timer t = new System.Timers.Timer();
t.Elapsed += new ElapsedEventHandler(TimerEvent);
t.Interval = 10000;
t.Start();
private bool RecordingStarted = false;
private void TimerEvent(object sender, ElapsedEventArgs e) {
if (RecordingStarted) {
VR.StopRecording(FileNameCounter++);
VR = null;
RecordingStarted = false;
} else {
VR = new VoiceRecording();
VR.StartRecording();
RecordingStarted = true;
}
}
Now the problem is when the code is executing inside TimerEvent, it is creating files but it is also missing some files.
For Example
Loop Creates: 1.wav, 2.wav, 3.wav, 4.wav, 5.wav, 6.wav
Timer Creates: 1.wav, 2.wav, 4.wav, 7.wav, 8.wav, 13.wav
I have debug the code, every statement is executing every time but sometimes the file is not being created.
Any help will be highly appreciated :)
As said by Hans Passant
System.Timers.Timer is a difficult class, creating all kinds of opportunity for undiagnosable failure. Re-entrancy is always a risk, its habit of swallowing all exceptions is especially troublesome. Just don't use it, you don't need it. Use a regular Winforms timer instead.
Using Winforms timer solved the problem. Now the numbered files are being created as I wanted them to be. :)
Thank You Hans Passant