gpt4 book ai didi

c# - 如何使用 naudio 将音频录制到 byte[] 而不是文件中

转载 作者:行者123 更新时间:2023-11-30 14:55:51 26 4
gpt4 key购买 nike

我能够使用 naudio 将音频捕获到文件中,现在我希望它在字节 [] 或 c# 中的 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();

但是当我尝试上述方式时,我得到了 System.ObjectDisposedException: 无法访问已关闭的流。在 memoryStream.Position = 0; 行上。我没有处理流对象,不知道它到底在哪里被处理。

最佳答案

正如 Mark 所建议的,我用 IgnoreDisposeStream 包装了 memoryStream 并且它起作用了。

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

关于c# - 如何使用 naudio 将音频录制到 byte[] 而不是文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24384493/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com