How to convert a MP3 file to WAV with NAudio in WinForms C#

How to convert a MP3 file to WAV with NAudio in WinForms C#

One of the biggest drawback of MP3 files is that they are just not good for looping as there will be always a small silent gap at the beginning and the end of the file. This is because the MP3 compression algorithm leaves a silent space of 10ms to 50ms at the start and end of the file. So if you try to loop the audio, you can hear a short pause at the looping point. In short words, you don’t get a seamless loop. The called encoder delay, the muted gap, occurs because the MP3 standard does not define a way to record the amount of delay or padding for later removal. This delay may also vary from encoder to encoder. This makes automatic removal difficult. Worse, even if two tracks are decompressed and merged into a single track, a gap will usually remain between them. That's one of the technical reasons why someone would like to always generate files in WAV format, however there are other simple reasons as programs that require only and specifically the WAV format instead of the MP3 one.

You can easily convert MP3 files into WAV using the widely known NAudio library, an audio and MIDI library for .NET following any of the offered options in this article. They're very straightforward and we're using them in the context of a WinForms application with a simple form that has a single button. The code that converts the MP3 files to WAV is executed when the user clicks on the button, attached to the button1_Click event. All of them follow the next logic: a MP3 file is opened with Mp3FileReader and then pass it to WaveFileWriter.CreateWaveFile to write the converted PCM audio to a WAV file. This will usually be 44.1kHz 16 bit stereo, but uses whatever format the MP3 decoder emits.

Requirements

You will need to install the NAudio library in your project using the NuGet package manager. Open your Winforms C# project and open the NuGet package manager in the solution explorer:

Go to the Browse tab and search for NAudio:

NAudio Install NuGet Package

From the list, select the NAudio package by Mark Heath and install it simply clicking on the Install button. Once the installation finishes you will be able to import the Wave namespace of NAudio in the class where you want to use it like this:

using NAudio.Wave;

If you already have NAudio installed, then proceed to convert your MP3 file using any of the following options:

Note

The option that you need to use depends totally on the host computer that runs the code. For example, the Mp3FileReader class uses the ACM MP3 codec that is present on almost all consumer versions of Windows. However, it is important to note that some versions of Windows Server do not have this codec installed without installing the "Desktop Experience" component.

A. Using the Mp3FileReader Class

The easiest way to convert an MP3 file to WAV is using the Mp3FileReader class that expects as first argument the path to the file that you want to convert. This will return a reader instance of the class, required by the important part to convert the file, the WaveFileWrite class, that offers a static method namely CreateWaveFile where convertion magic happens. This method expects as first argument the destination filepath and name of the WAV file and as second argument the reader of the MP3 file (that provides what content should be stored on the new file):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

// Import Wave of NAudio to use the Mp3FileReader
using NAudio.Wave;

namespace Sandbox
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Store the path of the file that you want to convert into a wav
            // as well its new path and name with extension
            string InputAudioFilePath = @"C:\Users\sdkca\Desktop\song.mp3";
            string OutputAudioFilePath = @"C:\Users\sdkca\Desktop\song_converted.wav";

            // Use the Mp3FileReader to obtain the content of the audio and use the wavfilewriter
            // to create the new file in wav format in the providen path with the content of the file
            using (Mp3FileReader reader = new Mp3FileReader(InputAudioFilePath))
            {
                WaveFileWriter.CreateWaveFile(OutputAudioFilePath, reader);
            }
        }
    }
}

B. Using the MediaFoundationReader class

MediaFoundationReader is a flexible class that allows you to read any audio file formats that Media Foundation supports. This typically includes MP3 on most consumer versions of Windows, but also usually supports WMA, AAC, MP4 and others. So unless you need to support Windows XP or are on a version of Windows without any Media Foundation condecs installed, this is a great choice. The logic is almost the same of the Mp3Reader class, create a reader and provide it as second argument of the CreateWaveFile method of the WaveFileWriter class:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

// Import Wave of NAudio to use the MediaFoundationReader
using NAudio.Wave;

namespace Sandbox
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Store the path of the file that you want to convert into a wav
            // as well its new path and name with extension
            string InputAudioFilePath = @"C:\Users\sdkca\Desktop\song.mp3";
            string OutputAudioFilePath = @"C:\Users\sdkca\Desktop\song_converted.wav";

            // Use the MediaFoundationReader class to obtain the content of the audio and use the wavfilewriter
            // to create the new file in wav format in the providen path with the content of the file
            using (MediaFoundationReader reader = new MediaFoundationReader(InputAudioFilePath))
            {
                WaveFileWriter.CreateWaveFile(OutputAudioFilePath, reader);
            }
        }
    }
}

C. Using the Mp3FileReader class with NLayer

If you want to use NLayer, the fully managed MP3 to WAV decoder, you need to install it as well using the NuGet package manager:

NLayer Mp3FileReader Installing with NuGet Package

After the installation you will be able to import the NAudioSupport class of NLayer that we'll use in our convertion process. The logic follows the same logic of the previous examples, however the Mp3FileReader class instance will receive as second argument in the constructor a lambda expression with a new instance of the Mp3FrameDecompressor class:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

// Import Wave of NAudio to use the MediaFoundationReader
using NAudio.Wave;
using NLayer.NAudioSupport;

namespace Sandbox
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Store the path of the file that you want to convert into a wav
            // as well its new path and name with extension
            string InputAudioFilePath = @"C:\Users\sdkca\Desktop\song.mp3";
            string OutputAudioFilePath = @"C:\Users\sdkca\Desktop\song_converted.wav";

            // Use the MediaFoundationReader class to obtain the content of the audio and use the wavfilewriter
            // to create the new file in wav format in the providen path with the content of the file
            using (Mp3FileReader reader = new Mp3FileReader(InputAudioFilePath, wf => new Mp3FrameDecompressor(wf)))
            {
                WaveFileWriter.CreateWaveFile(OutputAudioFilePath, reader);
            }
        }
    }
}

Happy coding !

This could interest you

Become a more social person