问题
Please note This is NOT a duplicate of the other question linked. That uses classes I couldn't find, as detailed in my question below.
I'm trying to convert wma files to mp3. I need a solution that I can integrate into my code base, not rely on an external resource, so using ffmpeg isn't an option. I've been trying NAudio, but without any success.
One problem is that there seem to be two versions of NAudio around, and neither seems complete. The one you get from Nuget doesn't include the WMAFileReader class, so there's no way (that i can see) to read wma files. The version on github includes the WMAFileReader class, but doesn't seem to include the Mp3Writer class, nor the WaveLib class I've seen in many examples.
So, anyone know how I can get something that will do the job? I've wasted hours trying different code samples, but none of them seem to work with either version of NAudio I can find.
Ideally, I would like to do this in memory, but if I have to write to temporary disk files, it's not the end of the world.
Edit I just discovered that there are more NAudio nuget packages that extend the basic one. There is one for Lame and one for WMA, but even after installing them, I can't get any code to work.
回答1:
Seems simple enough...
Create a new console project, use nuget
to add the NAudio.Lame
package (which I created to encapsulate the LAME
MP3 DLLs). I'm using the package direct from nuget
myself in this example.
Add the following method somewhere:
static void ConvertToMP3(string sourceFilename, string targetFilename)
{
using (var reader = new NAudio.Wave.AudioFileReader(sourceFilename))
using (var writer = new NAudio.Lame.LameMP3FileWriter(targetFilename, reader.WaveFormat, NAudio.Lame.LAMEPreset.STANDARD))
{
reader.CopyTo(writer);
}
}
Call that with the filename of your WMA file (or any other audio file readable by the AudioFileReader
class) and the filename you want to save to and let it run:
static void Main(string[] args)
{
ConvertToMP3(@"C:\temp\test.wma", @"C:\temp\test_transcode.mp3");
}
Where this might run into problems is when your input file is in a format that the MP3 encoder doesn't support. Weird channel counts, sample formats or sample rates can all cause the MP3 writer to fail. My test file was 44.1KHz Mono IEEE-float format when decoded, which the Lame codec is quite happy to work with. If you find one where it doesn't work then you'll have to do some sample conversion to get your input data into a compatible format.
Also you might want to play around with the quality parameter in the LameMP3FileWriter
constructor. There are a variety of presets (as defined in the LAME encoder itself) or you can try a direct specification of kilobits per second if you prefer. NAudio.Lame.LAMEPreset.STANDARD
produces a 128Kbps file.
来源:https://stackoverflow.com/questions/31232224/how-to-convert-from-wma-to-mp3-using-naudio