naudio

How to process audio files in .NET with NAudio

  • 3 min

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 are WAV, MP3, AAC, WMA, among others. Furthermore, it 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, which 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 via 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 a WAV format audio file:

Copy code
using NAudio.Wave;

var waveOut = new WaveOut();
var audioFile = new AudioFileReader("file.wav");

waveOut.Init(audioFile);
waveOut.Play();
Copied!

This code creates an instance of the WaveOut class and an AudioFileReader object that reads the specified audio file. Then, WaveOut is initialized with the AudioFileReader and the audio is played.

Process Audio in Real-Time with NAudio

To process audio in real-time with NAudio, you can use the WaveStream class and the effect and audio processor 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();
Copied!

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 containing the reverb effect.