我正在学习使用 naudio 进行音频编程(使用教程)。我的程序(C# .net winForms)我有录制和停止按钮。代码如下所示:
NAudio.Wave.WaveIn sourceStream = null;
NAudio.Wave.WaveFileWriter waveWriter = null;
private void RecordButton_Click(object sender, EventArgs e)
{
int deviceNumber = 0;
sourceStream = new NAudio.Wave.WaveIn();
sourceStream.DeviceNumber = deviceNumber;
sourceStream.WaveFormat = new NAudio.Wave.WaveFormat(44100, NAudio.Wave.WaveIn.GetCapabilities(deviceNumber).Channels);
sourceStream.DataAvailable += new EventHandler<NAudio.Wave.WaveInEventArgs>(sourceStream_DataAvailable);
waveWriter = new NAudio.Wave.WaveFileWriter("d:\\a.wav", sourceStream.WaveFormat);
sourceStream.StartRecording();
}
private void sourceStream_DataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
{
if (waveWriter == null) return;
waveWriter.WriteData(e.Buffer, 0, e.BytesRecorded);
waveWriter.Flush();
}
private void StopButton_Click(object sender, EventArgs e)
{
waveWriter.Dispose();
waveWriter = null;
}
它可以工作,但波形文件质量不好 - 我录制的声音有小间隙。我想要 44100 Hz 的采样率和 16 位的采样格式。