NAudio is an open-source library for .NET that allows us to work with audio files and recording on Windows. With NAudio, we can play, record, and process audio in a variety of formats.
Among the supported audio file formats, we find WAV, MP3, AAC, WMA, among others. It also provides the ability to encode and decode audio, as well as add filters or transformations.
NAudio also provides a variety of audio effects and processors, such as reverb, chorus, delay, and EQ, that you can use to manipulate audio in real time.
How to use NAudio
To use NAudio in your project, you must first download and add the library to your Visual Studio solution. You can download the library from the NAudio GitHub page or through the NuGet package manager.
Install-Package NAudio
NAudio is built around the WaveStream class, which represents a real-time audio stream or an audio file. We can use WaveStream to play or record audio, or process audio in real time.
To play audio, NAudio provides the WaveOut class, which sends the audio stream to the system’s audio output. To record audio, you can use the WaveIn class, which captures the audio stream from the system’s audio input.
Here is a simple example that plays an audio file in WAV format:
Copy code
using NAudio.Wave;
var waveOut = new WaveOut();
var audioFile = new AudioFileReader("file.wav");
waveOut.Init(audioFile);
waveOut.Play();
This code creates an instance of the WaveOut class and an AudioFileReader object that reads the specified audio file. Then, WaveOut is initialized with AudioFileReader and the audio is played.
How can I process audio in real time with NAudio? To process audio in real time with NAudio, you can use the WaveStream class and the audio effects and processors classes provided by the library. Here is an example that adds a reverb effect to a real-time audio stream:
Copy code
using NAudio.Wave;
var waveIn = new WaveIn();
var waveOut = new WaveOut();
var input = new WaveInProvider(waveIn);
var reverb = new ReverbEffect();
var output = new EffectStream(reverb, input);
waveOut.Init(output);
waveIn.StartRecording();
waveOut.Play();
This code creates an instance of the WaveIn class, which captures the audio stream from the system’s audio input, and an instance of the WaveOut class, which sends the audio stream to the system’s audio output. Then, a WaveInProvider object is created that sends the captured audio stream to an EffectStream object that contains the reverb effect.
NAudio is an open-source library, and all the code is available on the project’s website at https://github.com/naudio/NAudio