我在使用 naudio 和保存录音时遇到了一些问题。我目前拥有的代码可以保存 wav 文件,但是当我打开它时,Windows Media Player 返回错误:“Windows Media Player 在播放文件时遇到问题”
我有两个按钮,一个“录制”按钮,按下后变成停止按钮。我有一个“保存”按钮,单击该按钮会将录音保存到sample.wav
.
NAudio.Wave.WaveIn sourceStream = null;
NAudio.Wave.DirectSoundOut waveOut = null;
NAudio.Wave.WaveFileWriter waveWriter = null;
private void recordButton_Click(object sender, EventArgs e)
{
int deviceNumber = sourceList.SelectedItems[0].Index;
sourceStream = new NAudio.Wave.WaveIn();
sourceStream.DeviceNumber = deviceNumber;
sourceStream.WaveFormat = new NAudio.Wave.WaveFormat(44100, NAudio.Wave.WaveIn.GetCapabilities(deviceNumber).Channels);
NAudio.Wave.WaveInProvider waveIn = new NAudio.Wave.WaveInProvider(sourceStream);
waveOut = new NAudio.Wave.DirectSoundOut();
waveOut.Init(waveIn);
sourceStream.StartRecording();
waveOut.Play();
recordButton.Visible = false;
stopRecord.Visible = true;
}
private void saveResponse_Click(object sender, EventArgs e)
{
int deviceNumber = sourceList.SelectedItems[0].Index;
string saveLocation = "c:\\wav\\sample.wav";
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(saveLocation, sourceStream.WaveFormat);
sourceStream.StartRecording();
MessageBox.Show("Recording successfully saved.");
}
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 stopRecord_Click(object sender, EventArgs e)
{
if (waveOut != null)
{
waveOut.Stop();
waveOut.Dispose();
waveOut = null;
}
if (sourceStream != null)
{
sourceStream.StopRecording();
sourceStream.Dispose();
sourceStream = null;
}
if (waveWriter != null)
{
waveWriter.Dispose();
waveWriter = null;
}
recordButton.Visible = true;
stopRecord.Visible = false;
saveResponse.Enabled = true;
}