从naudio.Wave.WaveIn到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 a Stream [从WaveIn转换为Stream])?

请你们解释一下代码……我试过NAudio网站的解释,但我不明白 – >我是音频和流媒体的初学者……

您需要捕获DataAvailable提供的DataAvailable event ,类似这样

 //Initialization of the event handler for event DataAvailable sourceStream.DataAvailable += new EventHandler(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!