NAudio
NAudio copied to clipboard
Suggestion - Record and Playback Tutorial w/Example Code
I just started playing around with NAudio a few hours ago and one of the things I wanted to do is stream audio from my mic to my speaker. It took me a while to figure how to do it and I didn't see it listed anywhere. I didn't want to overstep any bounds by editing anything, so I will post my code here and you may add it to the wiki or something.
What We Will Need
This example was tested creating a generic form with two buttons: Start Broadcasting and Stop Broadcasting. We will need three classes WaveInEvent (Recorder), BufferedWaveProvider (Sound), WaveOutEvent (Playback). We will also need three functions, one to start broadcasting, to end and the process the data recorded from the mic. Since I had buttons controlling when we were recording, I also had a Recording bool property, and an Init bool property to avoid memory leakage to only initialize once.
Code
So first we need to initialize our Recorder, Sound and Playback. I did it in the form constructor and it looked something like this:
public Form1() {
InitializeComponent();
Recorder = new WaveInEvent {
WaveFormat = new WaveFormat(48000, 2)
};
Recorder.DataAvailable += ProcessData;
Sound = new BufferedWaveProvider(Recorder.WaveFormat);
Playback = new WaveOutEvent();
}
Since I had buttons controlling when the we were broadcasting the recorded mic audio, the functions took the relevant arguments.
private void StartBroadcast(object sender, EventArgs e) {
if (Recoding) return;
Recoding = true;
Recorder.StartRecording();
if(!Init) {
Playback.Init(Sound);
Init = true;
}
Playback.Play();
}
private void EndBroadcast(object sender, EventArgs e) {
if (!Recoding) return;
Recoding = false;
Recorder.StopRecording();
Playback.Stop();
}
private void ProcessData(object sender, WaveInEventArgs e) {
Sound.AddSamples(e.Buffer, 0, e.BytesRecorded);
}
And that's it. The code only requires slight modification for non-form applications or applications that don't use buttons. I feel like this should be the expected usage, but if something is wrong with the code, let me know.
Thanks for this