来自麦克风迭代结果的缓冲流

问题描述 投票:0回答:1

我想做的是,不断地听麦克风,让麦克风作者将其写入流中,当流的长度为x时,产生结果,清除流并继续循环进行。然后从呼叫者分析接收到的所有字节,我对麦克风录音有点陌生,我不知道下面的代码是否注册了某些东西,我正在使用NAudio库:

这是呼叫者:

var buffers = service.StreamHearing();
foreach (var buffer in buffers)
{
    //analyse
}

然后是实际服务:

public IEnumerable<byte[]> StreamHearing()
    {
        var buffer = new byte[512];
        using(var stream = new MemoryStream(buffer))
        using(var writer = new WaveFileWriter(new IgnoreDisposeStream(stream), new WaveFormat(44100, 1)))
        {
            var recorder = new WaveInEvent
            {
                WaveFormat = new WaveFormat(44100, 1),
                BufferMilliseconds = 100
            };

            recorder.StartRecording();
            while (true)
            {
                yield return buffer;
                buffer = new byte[512];
                stream.SetLength(0);
            }
        }
    }

这不起作用,请帮助我。谢谢

c# asp.net .net naudio
1个回答
0
投票

您需要了解几件您错过的事情。首先,WaveInEvent将异步写入麦克风中的数据。这是用于将数据从麦克风写入某些流的正确代码段:

var buffer = new byte[512];
var recorder = new WaveInEvent
{
   WaveFormat = new WaveFormat(44100, 1),
   BufferMilliseconds = 100
};
var stream = new MemoryStream(buffer);
var writer = new WaveFileWriter(new IgnoreDisposeStream(stream), recorder.WaveFormat);
recorder.DataAvailable += (source, eventArgs) => 
{
    var data = eventArgs.Buffer;
    var bytesRead = eventArgs.BytesRecorded;
    //here is a place where data from the microphone will be available
    //you can add your processing right here in case you don't need to record and save the data
    writer.Write(data, 0, bytesRead);
};

waveIn.StartRecording(); 
© www.soinside.com 2019 - 2024. All rights reserved.