How do can I use LAME to encode an wav to an mp3 c#

user2843871 picture user2843871 · Oct 3, 2013 · Viewed 14.9k times · Source

I am currently using NAudio to capture the sound and it only creates a wav file. I am looking for a way to encode it to an mp3 before saving the file. I found LAME but when ever i try to add the lame_enc.dll file it says "A reference could not be added. Please make sure the file is accessible, and that is a valid assembly or COM component". Any help would be appreciated.

Answer

JJ_Coder4Hire picture JJ_Coder4Hire · May 30, 2014

Easiest way in .Net 4.0:

Use the visual studio Nuget Package manager console:

Install-Package NAudio.Lame

Code Snip: Send speech to a memory stream, then save as mp3:

//reference System.Speech
using System.Speech.Synthesis; 
using System.Speech.AudioFormat;

//reference Nuget Package NAudio.Lame
using NAudio.Wave;
using NAudio.Lame; 


using (SpeechSynthesizer reader = new SpeechSynthesizer()) {
    //set some settings
    reader.Volume = 100;
    reader.Rate = 0; //medium

    //save to memory stream
    MemoryStream ms = new MemoryStream();
    reader.SetOutputToWaveStream(ms);

    //do speaking
    reader.Speak("This is a test mp3");

    //now convert to mp3 using LameEncoder or shell out to audiograbber
    ConvertWavStreamToMp3File(ref ms, "mytest.mp3");
}

public static void ConvertWavStreamToMp3File(ref MemoryStream ms, string savetofilename) {
    //rewind to beginning of stream
    ms.Seek(0, SeekOrigin.Begin);

    using (var retMs = new MemoryStream())
    using (var rdr = new WaveFileReader(ms))
    using (var wtr = new LameMP3FileWriter(savetofilename, rdr.WaveFormat, LAMEPreset.VBR_90)) {
        rdr.CopyTo(wtr);
    }
}