I'm coding a soundboard using NAudio as a library to manage my audio. One of the features I want to implement is the ability to be continuously recording one (or many) audio inputs and be able, at any time to save them.
The way I see this possible is by keeping a circular buffer of the last ex: 5s of samples picked up by the audio input.
I also want to avoid keeping all the data up to the point when it started as I dont want to overuse memory.
I've tried many approches to this problem:
- Using a circular buffer and feed it with data from "DataAvailable" event;
- Using "Queue" and "BufferedWaveProvider" to add the buffer data and transform it into a sample.
- I tried using 2 "BufferedWaveProvider" and alternating wich was getting filled depending on which was full.
- I also tried to use 2 wave inputs and timers to alternate which was recording.
I tried using an array of bytes and use it as a circular buffer. I filled the buffer using the "DataAvailable" event from "WaveInEvent". The "WaveInEventArgs" has a buffer so I added the data from it to the circular buffer.
private int _start = 0, _end = 0;
private bool _filled = false;
private byte[] _buffer; // the size was set in the constructor
// its an equation to figure out how many samples
// a certain time needs.
private void _dataAvailable(object sender, WaveInEventArgs e)
{
for (int i = 0; i < e.BytesRecorded; i++)
{
if (_filled)
{
_start = _end + 1 > _buffer.Length - 1 ? _end + 1 : 0;
}
if (_end > _buffer.Length - 1 && !_filled) _filled = true;
_end = _end > _buffer.Length - 1 ? _end + 1 : 0;
_buffer[_end] = e.Buffer[i];
}
}
Some of the attempts i made kind of worked but, most of the time, they would work for the first 5 seconds (I am aware that using a "BufferredWaveProvider" can cause that issue. I think that part of the problem is that there is a certain amount of data that is required at the beginning of the buffer, and as soon as the buffer starts overwriting that data, the audio player doesn
Another very possible cause of the problem is that i'm just starting to use NAudio and don't quite understand it fully yet.
I've been stuck with this issue for a while now and I appreciate all the help anyone can give me.
I have some more code that I could add, but I thought this question was already getting long.
Thank you in advance!
WaveInEvent
keeps any data. Check the description of the class and/or documentation. Also make sure to dispose both wave in and out objects (if they are disposable). Other than that... it's okay. – GregorMohorko