gpt4 book ai didi

c# - 使用Windows Timer耗时事件的音频录制问题

转载 作者:行者123 更新时间:2023-12-03 00:50:41 25 4
gpt4 key购买 nike

我正在按时间间隔从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

我已经调试了代码,每条语句每次都在执行,但有时未创建文件。

任何帮助将不胜感激:)

最佳答案

正如汉斯·帕桑特(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.



使用Winforms计时器解决了该问题。现在,编号文件正在按我希望的方式创建。 :)

谢谢 Hans Passant

关于c# - 使用Windows Timer耗时事件的音频录制问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21580333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com