如何使用naudio记录音频到字节[]而不是文件

本文关键字:文件 到字节 何使用 naudio 记录 音频 | 更新日期: 2023-09-27 18:10:00

我能够使用naudio捕获音频到文件中,现在我希望它在c#中的byte[]或Stream .

this.writer = new WaveFileWriter(this.outputFilename, this.waveIn.WaveFormat);

到目前为止,我所尝试的不是在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;
    } 
}

出于测试目的,我创建了下面的代码来检查它是否能够播放录制的音频。

System.Media.SoundPlayer soundPlayer = new System.Media.SoundPlayer();
memoryStream.Position = 0; 
soundPlayer.Stream = null;
soundPlayer.Stream = memoryStream;
soundPlayer.Play();

但是当我用上面的方式尝试时,我得到了系统。无法访问已关闭的流。在memoryStream这行。 .我没有处理流对象,不知道在哪里处理

如何使用naudio记录音频到字节[]而不是文件

正如Mark建议的那样,我用IgnoreDisposeStream包装了memoryStream,并且它有效。

this.writer = new WaveFileWriter(new IgnoreDisposeStream(memoryStream),this.waveIn.WaveFormat);

不要创建内存流。使用System.Media.SoundPlayer作为流媒体。

byte[] buff = new byte[1024];   //or bigger...
System.Media.SoundPlayer soundPlayer = new System.Media.SoundPlayer();
soundPlayer.Stream.Read(buff, 0, (buff.Length - 1));

SoundPlayer类不是很适合这个,因为它在开始播放之前读取整个流。它还要求流是Wave文件格式,所以你必须使用WaveFileWriter将所有音频数据写出来,然后才能与SoundPlayer一起使用流。

我建议你使用NAudio的WaveOutEvent(或类似的)来做你的音频输出。这样做消除了对流的需求,并允许你在接近实时的情况下播放录制的音频(它会有延迟;具体多少取决于您的硬件和所涉及的所有缓冲区的大小)。