如何使用naudio将音频录制到byte []而不是文件上 [英] How to record audio using naudio onto byte[] rather than file
问题描述
我现在可以使用naudio将音频捕获到文件中,现在我希望将其存储在byte []或c#中的Stream上.
I am able to capture audio using naudio into file, now i want it on byte[] or Stream in c#.
this.writer = new WaveFileWriter(this.outputFilename, this.waveIn.WaveFormat);
到目前为止,我尝试的不是在WaveFileWriter构造函数中传递输出文件名,而是传递MemoryStream对象.对于流对象,我尝试在录音结束后使用Soundplayer播放它.
What i tried so far is instead of passing output filename in WaveFileWriter constructor, passed MemoryStream object. With reference to stream object i try to play it using Soundplayer once recording gets over.
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;
}
}
出于测试目的,我在下面的代码中创建了此代码,以检查其是否可以播放录制的音频.
For testing purpose, i created this below code to check whether it able to play the recorded audio.
System.Media.SoundPlayer soundPlayer = new System.Media.SoundPlayer();
memoryStream.Position = 0;
soundPlayer.Stream = null;
soundPlayer.Stream = memoryStream;
soundPlayer.Play();
但是当我尝试上述方式时,出现了System.ObjectDisposedException:无法访问封闭的Stream.在 memoryStream.Position = 0; 上.我没有处理流对象,也不知道它在哪里处理.
But when i try with above manner, i got System.ObjectDisposedException: Cannot access a closed Stream. On the line memoryStream.Position = 0; .I didn't dispose the stream object, Don't know where exactly it gets disposed.
推荐答案
正如Mark所建议的,我用IgnoreDisposeStream
包裹了memoryStream
并且它起作用了.
As Mark suggests, i wrapped the memoryStream
with IgnoreDisposeStream
and it works.
this.writer = new WaveFileWriter(new IgnoreDisposeStream(memoryStream),this.waveIn.WaveFormat);
这篇关于如何使用naudio将音频录制到byte []而不是文件上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!