2013-10-03 58 views
6

我目前使用NAudio來捕捉聲音,並且它只創建一個wav文件。我正在尋找一種在保存文件之前將其編碼爲mp3的方法。我發現LAME,但是當我嘗試添加lame_enc.dll文件時,它說「無法添加引用,請確保該文件可訪問,並且這是一個有效的程序集或COM組件」。任何幫助,將不勝感激。如何使用LAME將wav編碼爲mp3 c#

+1

http://www.codeproject.com/Articles/501521/How-to-convert-between-most-audio-formats-in-NET – MichaC

回答

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; 
     } 
     } 
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。這應該讓你開始。

8

在.NET 4.0中最簡單的方法:

使用Visual Studio的NuGet包管理器控制檯:

Install-Package NAudio.Lame 

代碼剪斷:發送語音到內存流,然後保存爲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); 
    } 
} 
+2

retMs在這個例子中沒有做什麼? –

相關問題