【发布时间】:2014-03-02 01:35:06
【问题描述】:
我正在按时间间隔从我的 Windows 应用程序录制语音。我创建了一个类来开始和停止录音并在我的表单上调用它的功能。
类如下
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();
}
}
现在,当我在按钮单击事件上调用这些函数时,例如
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;
}
一切正常,无论我点击按钮多慢或多快,代码总是会创建编号文件。
我也将代码放入循环中
for (int i = 0; i < 10; i++) {
VR = new VoiceRecording();
VR.StartRecording();
VR.StopRecording(FileNameCounter++);
VR = null;
}
它也运行良好并创建了 10 个编号的文件。
到现在为止一切都很好,这里我就这样介绍了Timer
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;
}
}
现在的问题是当代码在 TimerEvent 中执行时,它正在创建文件,但也缺少一些文件。
例如
循环创建:1.wav、2.wav、3.wav、4.wav、5.wav、6.wav
定时器创建:1.wav、2.wav、4.wav、7.wav、8.wav、13.wav
我已经调试过代码,每条语句每次都在执行,但有时文件没有被创建。
任何帮助将不胜感激:)
【问题讨论】:
-
没有这方面的经验,但是在您的 VoiceRecording 类中,您正在向某个底层对象发送消息而不检查是否成功 - 寻找获取状态/检索错误的方法是我开始的地方。
-
System.Timers.Timer 是一个困难的类,为无法诊断的故障创造了各种机会。重入总是有风险的,它吞下所有异常的习惯尤其麻烦。只是不要使用它,你不需要它。请改用常规的 Winforms 计时器。
标签: c# audio timer voice-recording elapsed