using System; using NAudio.Wave; namespace XHWK.WKTool.Utils { public class ZAudioRecordHelper { public enum RecordType { loudspeaker = 0, // 扬声器 microphone = 1 //麦克风 } public enum RecordState { stop = 0, start = 1, pause = 2 } //录制的类型 RecordType _t = RecordType.microphone; RecordState _state = RecordState.stop; //录制麦克风的声音 WaveInEvent waveIn = null; //new WaveInEvent(); //录制扬声器的声音 WasapiLoopbackCapture capture = null; //new WasapiLoopbackCapture(); //生成音频文件的对象 WaveFileWriter writer = null; string audioFile = ""; public ZAudioRecordHelper(string filePath,RecordType type) { _t = type; audioFile = filePath; } /// /// 开始录制 /// public void StartRecordAudio() { _state = RecordState.start; try { if (_t == RecordType.microphone) { waveIn = new WaveInEvent(); writer = new WaveFileWriter(audioFile, waveIn.WaveFormat); //开始录音,写数据 waveIn.DataAvailable += (s, a) => { if (_state == RecordState.start) { writer.Write(a.Buffer, 0, a.BytesRecorded); } }; //结束录音 waveIn.RecordingStopped += (s, a) => { writer.Dispose(); writer = null; waveIn.Dispose(); }; waveIn.StartRecording(); } else { capture = new WasapiLoopbackCapture(); writer = new WaveFileWriter(audioFile, capture.WaveFormat); capture.DataAvailable += (s, a) => { if (_state == RecordState.start) { writer.Write(a.Buffer, 0, a.BytesRecorded); } }; //结束录音 capture.RecordingStopped += (s, a) => { writer.Dispose(); writer = null; capture.Dispose(); }; capture.StartRecording(); } } catch (Exception ex) { } } /// /// 结束录制 /// public void StopRecordAudio() { _state = RecordState.stop; if (_t == RecordType.microphone) { waveIn.StopRecording(); } else { capture.StopRecording(); } } /// /// 暂停录制 /// public void PauseRecordAudio() { _state = RecordState.pause; } /// /// 恢复录制 /// public void ResumeRecordAudio() { _state = RecordState.start; } } }