0

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

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

任何帮助将不胜感激:)

4

1 回答 1

1

正如汉斯·帕桑特所说

System.Timers.Timer 是一个困难的类,为无法诊断的故障创造了各种机会。重入总是有风险的,它吞下所有异常的习惯尤其麻烦。只是不要使用它,你不需要它。请改用常规的 Winforms 计时器。

使用 Winforms 计时器解决了这个问题。现在正在按照我想要的方式创建编号文件。:)

谢谢你汉斯帕桑特

于 2014-02-06T07:52:16.310 回答