這是我用它來錄製音頻文件中的代碼:使用記錄波形文件(n音訊)
internal class AudioRecorder
{
public WaveIn waveSource = null;
public WaveFileWriter waveFile = null;
public string RECORDING_PATH;
public AudioRecorder(string fileName)
{
RECORDING_PATH = fileName;
}
public void Start()
{
waveSource = new WaveIn();
waveSource.WaveFormat = new WaveFormat(44100, 1);
waveSource.DeviceNumber = 0;
waveSource.DataAvailable += new EventHandler<WaveInEventArgs>(waveSource_DataAvailable);
waveSource.RecordingStopped += new EventHandler<StoppedEventArgs>(waveSource_RecordingStopped);
waveFile = new WaveFileWriter(RECORDING_PATH, waveSource.WaveFormat);
System.Timers.Timer t = new System.Timers.Timer(30000);
t.Elapsed += new ElapsedEventHandler(Stop);
waveSource.StartRecording();
t.Start();
}
private void Stop(object sender, ElapsedEventArgs args)
{
waveSource.StopRecording();
}
private void waveSource_DataAvailable(object sender, WaveInEventArgs e)
{
if (waveFile != null)
{
waveFile.Write(e.Buffer, 0, e.BytesRecorded);
waveFile.Flush();
}
}
private void waveSource_RecordingStopped(object sender, StoppedEventArgs e)
{
if (waveSource != null)
{
waveSource.Dispose();
waveSource = null;
}
if (waveFile != null)
{
waveFile.Dispose();
waveFile = null;
}
}
}
在main方法我做的:
AudioRecorder r = new AudioRecorder(dialog.FileName);
r.Start();
FileInfo file = new FileInfo(r.RECORDING_PATH);
// Do somehting with the recorded audio //
的問題是,當我做r.Start()
線程不會阻塞並繼續運行。所以我得到一個損壞的文件錯誤。當我嘗試使用Thread.Sleep
等線程等待記錄結束時,此時AudioRecorder
代碼無法正常工作(即錄製從未結束)。
關於我應該怎麼做的任何想法等待錄音完成,以便我可以安全地使用錄製的文件?
音頻錄製現在已成功完成並且沒有損壞。但是,它沒有記錄它應該的長度(即30秒)。我得到的是1秒的白噪聲。 – Cemre
Windows消息泵需要運行才能執行引發的事件。這個黑客工程,但你最好提出一個事件RecordingComplete或類似的東西... – rene