You can use LameMP3FileWriter
from NAudio.Lame
to do the encoding by treating it as a Stream
and writing samples to it.
Here's an off-the-cuff example:
LameMP3FileWriter mp3writer = null;
WaveFormat mp3format = null;
public void StartMP3Encoding(string filename, WaveFormat format)
{
if (mp3writer != null)
StopMP3Encoding();
mp3format = format;
mp3writer = new LameMP3FileWriter(filename, format, 128);
}
public void StopMP3Encoding()
{
if (mp3writer != null)
{
mp3writer.Dispose();
mp3writer = null;
}
}
public int EnqueueSamples(int channels, int rate, byte[] samples, int frames)
{
if (mp3writer != null && mp3format.Channels == channels)
mp3writer.Write(samples, 0, samples.Length);
return frames;
}
When you want to start recording the MP3 file call StartMP3Encoding
with the file name to record to and the format of the data. When done, call StopMP3Encoding
to close the encoder. In between, write your incoming samples as and when they arrive.
The LAME encoder isn't time-precious so you can dribble data to it as slow as you like or blast it with data as quickly as it will take it.
There are a few limitations in the combinations of input sample rate and output bitrate imposed by the LAME encoder, but it handles a fair variations on standard values.