| 12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- using NAudio.Wave;
- namespace ScreenRecorder;
- /// <summary>
- /// 录制系统麦克风音频,保存为 WAV 文件
- /// </summary>
- public class AudioService : IDisposable
- {
- private WaveInEvent? _waveIn;
- private WaveFileWriter? _writer;
- private string? _outputPath;
- public void Start(string outputPath)
- {
- _outputPath = outputPath;
- _waveIn = new WaveInEvent
- {
- WaveFormat = new WaveFormat(44100, 1),
- BufferMilliseconds = 50
- };
- _writer = new WaveFileWriter(outputPath, _waveIn.WaveFormat);
- _waveIn.DataAvailable += OnDataAvailable;
- _waveIn.StartRecording();
- }
- private void OnDataAvailable(object? sender, WaveInEventArgs e)
- {
- _writer?.Write(e.Buffer, 0, e.BytesRecorded);
- }
- public void Stop()
- {
- _waveIn?.StopRecording();
- _waveIn?.Dispose();
- _waveIn = null;
- _writer?.Dispose();
- _writer = null;
- }
- public void Dispose() => Stop();
- }
|