我能够使用naudio将音频捕获到文件中,现在我希望它在byte []或stream in c#中.
this.writer = new WaveFileWriter(this.outputFilename, this.waveIn.WaveFormat);
Run Code Online (Sandbox Code Playgroud)
到目前为止我尝试的是在WaveFileWriter构造函数中传递输出文件名,而不是传递MemoryStream对象.参考流对象,一旦录制结束,我尝试使用Soundplayer播放它.
private IWaveIn waveIn;
private WaveFileWriter writer;
private string outputFilename;
private Stream memoryStream;
public void onRecord(object inputDevice, string fileName)
{
if (this.waveIn == null)
{
this.outputFilename = fileName;
this.waveIn = new WasapiLoopbackCapture((MMDevice)inputDevice);
if(memoryStream == null)
memoryStream = new MemoryStream();
this.writer = new WaveFileWriter(this.memoryStream,this.waveIn.WaveFormat);
this.waveIn.DataAvailable += new EventHandler<WaveInEventArgs>(this.OnDataAvailable);
this.waveIn.RecordingStopped += new EventHandler<StoppedEventArgs>(this.OnRecordingStopped);
this.waveIn.StartRecording();
}
}
private void OnDataAvailable(object sender, WaveInEventArgs e)
{
this.writer.Write(e.Buffer, 0, e.BytesRecorded);
}
public void OnRecordingStopped(object sender, StoppedEventArgs e)
{
if (this.waveIn != null)
{
this.waveIn.Dispose();
this.waveIn = null;
}
if (this.writer != null)
{
this.writer.Close();
this.writer = null;
}
}
Run Code Online (Sandbox Code Playgroud)
出于测试目的,我创建了以下代码以检查它是否能够播放录制的音频.
System.Media.SoundPlayer soundPlayer = new System.Media.SoundPlayer();
memoryStream.Position = 0;
soundPlayer.Stream = null;
soundPlayer.Stream = memoryStream;
soundPlayer.Play();
Run Code Online (Sandbox Code Playgroud)
但是当我尝试以上方式时,我得到System.ObjectDisposedException:无法访问封闭的Stream.在行memoryStream.Position = 0; 我没有丢弃流对象,不知道它究竟在哪里处理.
正如马克暗示,我的包裹memoryStream与IgnoreDisposeStream和它的作品.
this.writer = new WaveFileWriter(new IgnoreDisposeStream(memoryStream),this.waveIn.WaveFormat);
Run Code Online (Sandbox Code Playgroud)