我的动机是使用NAudio录制音频,保存为wav文件,然后混合多个音频和播放。为此我试过
private void buttonRecord_Click(object sender, EventArgs e)
{
//if (sourceList.SelectedItems.Count == 0) return;
//int deviceNumber = sourceList.SelectedItems[0].Index;
sourceStream = new NAudio.Wave.WaveIn();
sourceStream.DeviceNumber = 0;
sourceStream.WaveFormat = new NAudio.Wave.WaveFormat(44100, NAudio.Wave.WaveIn.GetCapabilities(0).Channels);
sourceStream1 = new NAudio.Wave.WaveIn();
sourceStream1.DeviceNumber = 1;
sourceStream1.WaveFormat = new NAudio.Wave.WaveFormat(44100, NAudio.Wave.WaveIn.GetCapabilities(1).Channels);
//NAudio.Wave.WaveInProvider waveIn = new NAudio.Wave.WaveInProvider(sourceStream);
//sourceStream.StartRecording();
//waveOut.Play();
sourceStream1.DataAvailable += new EventHandler<NAudio.Wave.WaveInEventArgs>(waveIn_DataAvailable1);
writer1 = new NAudio.Wave.WaveFileWriter("D:\test.wav", sourceStream1.WaveFormat);
sourceStream1.StartRecording();
sourceStream.DataAvailable += new EventHandler<NAudio.Wave.WaveInEventArgs>( waveIn_DataAvailable);
writer = new NAudio.Wave.WaveFileWriter("D:\test1.wav", sourceStream.WaveFormat);
sourceStream.StartRecording();
}
void waveIn_DataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
{
writer.WriteData(e.Buffer, 0, e.BytesRecorded);
}
void waveIn_DataAvailable1(object sender, NAudio.Wave.WaveInEventArgs e)
{
writer1.WriteData(e.Buffer, 0, e.BytesRecorded);
}
private void buttonStopRecording_Click(object sender, EventArgs e)
{
if (sourceStream != null)
{
sourceStream.StopRecording();
sourceStream.Dispose();
sourceStream = null;
}
if (sourceStream1 != null)
{
sourceStream1.StopRecording();
sourceStream1.Dispose();
sourceStream1 = null;
}
}
以上代码非常适合录制,但录制的音频不能在Windows媒体播放器中播放,但适用于VLC媒体播放器。使用下面的代码我尝试混合
void Mixingfunction()
{
MixingSampleProvider mixer = new MixingSampleProvider(NAudio.Wave.WaveFormat.CreateIeeeFloatWaveFormat(44100, 1));
try
{
audioFileReader = new AudioFileReader(@"D:\test1.wav");
mixer.AddMixerInput((ISampleProvider)audioFileReader);
audioFileReader = new AudioFileReader(@"D:\test.wav");
mixer.AddMixerInput((ISampleProvider)audioFileReader);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
return;
}
waveOut = new NAudio.Wave.DirectSoundOut();
//if (flag == true)
//{
// mixer.AddMixerInput((ISampleProvider)sineWaveProvider);
//}
//SampleToWaveProvider mixer2 = new SampleToWaveProvider((ISampleProvider)mixer);
waveOut.Init((IWaveProvider)mixer);
waveOut.Play();
}
但它提供了异常no FMT Chunk found
。现在我不知道该做什么......
答案 0 :(得分:3)
您需要在准备好播放之前处置WaveFileWriter
个对象。这样做会更新WAV文件头中的块大小。