从 naudio.Wave.WaveIn 到 Stream ?

From naudio.Wave.WaveIn to Stream ?

我复制了这段代码,但我不明白它,但我知道它完成后会做什么(输出 -- sourceStream)...

 NAudio.Wave.WaveIn sourceStream = null;
 NAudio.Wave.DirectSoundOut waveOut = null;
  NAudio.Wave.WaveFileWriter waveWriter = null;

        sourceStream = new NAudio.Wave.WaveIn();
    sourceStream.DeviceNumber = 2;
    sourceStream.WaveFormat = new NAudio.Wave.WaveFormat(16000, NAudio.Wave.WaveIn.GetCapabilities(2).Channels);

    NAudio.Wave.WaveInProvider waveIn = new NAudio.Wave.WaveInProvider(sourceStream);

    waveOut = new NAudio.Wave.DirectSoundOut();
    waveOut.Init(waveIn);
    //sourceStream.DataAvailable.
    sourceStream.StartRecording();
    waveOut.Play();
    sourceStream.StopRecording();

据我所知,这段代码记录了来自选定麦克风的声音,并为其提供了输出 (sourceStream)

所以我需要做的第一件事是 --> 我怎样才能从这段代码中得到一个流(比如而不是 WaveIn 一个 Stream [从 WaveIn 转换为 Stream])?

你们能解释一下代码吗……我尝试了 NAudio 网站的解释,但我不明白 --> 我是音频和流的初学者……

您需要捕获 WaveIn 提供的 DataAvailable event,像这样

//Initialization of the event handler for event DataAvailable
sourceStream.DataAvailable += new EventHandler<WaveInEventArgs>(sourceStream_DataAvailable); 

并提供 event handler,您需要的数据在 event handlerWaveInEventArgs 输入参数中。请注意,音频的数据类型是 short 所以我通常会这样做,

private void sourceStream_DataAvailable(object sender, WaveInEventArgs e) {
  if (sourceStream == null)
    return;
  try {
    short[] audioData = new short[e.Buffer.Length / 2]; //this is your data! by default is in the short format
    Buffer.BlockCopy(e.Buffer, 0, audioData, 0, e.Buffer.Length);
    float[] audioFloat = Array.ConvertAll(audioData, x => (float)x); //I typically like to convert it to float for graphical purpose
    //Do something with audioData (short) or audioFloat (float)          
  } catch (Exception exc) { //if some happens along the way...
  }
}

但是,如果你想将它转换为byte[]格式,那么你应该直接使用e.Buffer或者将它复制到byte[]的一些更合适的地方.至于我复制到 byte[] 数组然后在其他地方处理它通常更合适,因为 WaveIn 流是活动的。

byte[] bytes = new short[e.Buffer.Length]; //your local byte[]
byteList.AddRange(bytes); //your global var, to be processed by timer or some other methods, I prefer to use List or Queue of byte[] Array

然后要将 byteList 转换为 Stream,您只需使用 MemoryStream 并输入 byte[]

Stream stream = new MemoryStream(byteList.ToArray()); //here is your stream!