Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

naudio

lame

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.

like image 363
user2843871 Avatar asked Oct 03 '13 18:10

user2843871


People also ask

Is LAME an MP3 encoder?

LAME is a software encoder that converts digital audio into the MP3 Audio coding format. LAME is a free software project that was first released in 1998, and has incorporated many improvements since then, including an improved psychoacoustic model.

Is LAME the best MP3 encoder?

Today, LAME is considered the best MP3 encoder at mid-high bitrates and at VBR, mostly thanks to the dedicated work of its developers and the open source licensing model that allowed the project to tap into engineering resources from all around the world.


2 Answers

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);
    }
}
like image 184
JJ_Coder4Hire Avatar answered Sep 28 '22 05:09

JJ_Coder4Hire


The file lame_enc.dll is an unmanaged DLL, meaning that you can't just add a reference to it in your .NET application. You need a wrapper to define what the entry points are and how they're called . For lame_enc.dll I use the Yeti wrapper, which can be found in the code attached to this CodeProject article.

I posted a step-by-step on how to use this for MP3 encoding in response the question: change format from wav to mp3 in memory stream in NAudio. That should get you started.

like image 43
Corey Avatar answered Sep 28 '22 05:09

Corey