我如何使用LAME将wav编码为mp3 c#

时间:2013-10-03 18:08:45

标签: c# naudio lame

我目前正在使用NAudio来捕获声音,它只会创建一个wav文件。我正在寻找一种方法,在保存文件之前将其编码为mp3。我找到了LAME,但是当我尝试添加lame_enc.dll文件时,它说“无法添加引用。请确保该文件是可访问的,这是一个有效的程序集或COM组件”。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:9)

.Net 4.0中的最简单方法:

使用visual studio Nuget Package Manager控制台:

Install-Package NAudio.Lame

Code Snip:将语音发送到内存流,然后另存为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);
    }
}

答案 1 :(得分:1)

只需将lame_enc.dll放在bin文件夹中,不要尝试将其添加到引用中。之后尝试此代码。在这里你也可以设置比特率如64,128,.....

    public byte[] ConvertWavToMP3(byte[] bt, uint bitrate)
    {         

        MemoryStream ms = new MemoryStream(bt);
        ms.Seek(0, SeekOrigin.Begin);
        var ws = new WaveFileReader(ms);

        byte[] wavdata = null;
        using (MemoryStream wavstrm = new MemoryStream())
        using (WaveFileWriter wavwri = new WaveFileWriter(wavstrm, ws.WaveFormat))
        {
            ws.CopyTo(wavwri);
            wavdata = wavstrm.ToArray();
        }

        WaveLib.WaveFormat fmt = new WaveLib.WaveFormat(ws.WaveFormat.SampleRate, ws.WaveFormat.BitsPerSample, ws.WaveFormat.Channels);

        Yeti.Lame.BE_CONFIG beconf = new Yeti.Lame.BE_CONFIG(fmt, bitrate);

        byte[] srm = null;

        using (MemoryStream mp3strm = new MemoryStream())
        using (Mp3Writer mp3wri = new Mp3Writer(mp3strm, fmt, beconf))
        {               
            mp3wri.Write(wavdata, 0, wavdata.Length);
            byte[] mp3data = mp3strm.ToArray();
            return mp3data;
        }
       }

答案 2 :(得分:1)

文件lame_enc.dll是一个非托管DLL,这意味着您不能在.NET应用程序中添加对它的引用。您需要一个包装器来定义入口点以及它们的调用方式。对于lame_enc.dll,我使用了Yeti包装器,该包装器可以在this CodeProject article.附带的代码中找到

我逐步介绍了如何将其用于MP3编码以回答问题:change format from wav to mp3 in memory stream in NAudio。这应该让你开始。