Convert PCM to MP3/OGG

此生再无相见时 提交于 2019-12-04 16:30:59

To answer your first question, to create MP3 or OGG you need an encoder. NAudio does not include an MP3 or an OGG encoder. All it does is give you ways to access encoders that are already installed on your computer (such as ACM or Media Foundation Transforms). However, with both MP3 and OGG you'll find that the easiest way is to find an unmanaged DLL or a command line utility and access that from .NET. The article I wrote which you linked to above includes a brief explanation of how you can use LAME.exe with stdin and stdout to convert PCM to MP3 on the fly.

As for your second question, the answer is yes. Whenever you transcode, you first decode to PCM, then re-encode in the target codec. I think theoretically you can put audio encoded in any format into an OGG container, but in practice, audio in an OGG container is usually encoded with Vorbis. FLAC and OPUS may be options, but once again you'd need to find an application or library that can write the OGG container format for you, as I'm not aware of any fully managed OGG writers.

<Shameless Plug>
I wrote an addon for NAudio that uses libmp3lame from the LAME Encoder suite to handle MP3 encoding. It's on NuGet as NAudio.Lame, and the source is on GitHub.
</Shameless Plug>

Sadly the licensing issues remain if you are planning to use this for anything other than personal use. LAME itself is licensed under the LGPL, but the patents it implements still require licencing from Frauenhofer/Thompson according to the LAME Wikipedia entry. If you're planning to produce something for others this can get expensive.

The Vorbis compressor is unencumbered by patents and such, so it's a reasonable alternative. At some point I plan to do a similar wrapper to the OGG/Vorbis format. In the meantime, a quick Google Search turns up the Ogg Vorbis Interop Library which might be useful to you.

And yes, you will need PCM as an intermediate format in pretty much any conversion. NAudio gives you the tools to get PCM from a wide variety of audio formats.

1) PCM to OGG

string fileName = @"e:\Down\male.wav";
Sox.Convert(@"sox.exe", fileName, fileName + ".ogg");

2) PCM to MP3

    static void AnyToMp3(string fileName)
    {
        DsReader dr = new DsReader(fileName);
        IntPtr formatPcm = dr.ReadFormat();
        byte[] dataPcm = dr.ReadData();
        dr.Close();
        IntPtr formatMp3 = AudioCompressionManager.GetCompatibleFormat(formatPcm,
            AudioCompressionManager.MpegLayer3FormatTag);
        byte[] dataMp3 = AudioCompressionManager.Convert(formatPcm, formatMp3, dataPcm, false);
        Mp3Writer mw = new Mp3Writer(File.Create(fileName + ".mp3"));
        mw.WriteData(dataMp3);
        mw.Close();
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!