从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 handler
的WaveInEventArgs
输入参数中。 请注意,音频的数据类型很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[]
上述就是C#学习教程:从naudio.Wave.WaveIn到Stream?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
Stream stream = new MemoryStream(byteList.ToArray()); //here is your stream!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/952400.html