如何使用C#将任何音频格式转换为MP3

时间:2012-10-05 15:41:30

标签: c#

我想播放用户上传的音频。上传的音频将采用任何格式。 有没有办法将任何音频文件转换为mp3格式?

1 个答案:

答案 0 :(得分:5)

您可以使用此功能 - 基于alvas component

链接:http://alvas.net/alvas.audio,tips.aspx#tip24

private void ConvertAudio()
    {
        string webFile = @"D:\AudioCS\bin\Debug\_web.mp3";
        string pcmFile = @"D:\AudioCS\bin\Debug\_AudioCS.wav";
        using (WaveReader wr = new WaveReader(File.OpenRead(pcmFile)))
        {
            IntPtr pcmFormat = wr.ReadFormat();
            byte[] pcmData = wr.ReadData();
            IntPtr webFormat = AudioCompressionManager.GetCompatibleFormat(pcmFormat,
            AudioCompressionManager.MpegLayer3FormatTag);
            byte[] webData = AudioCompressionManager.Convert(pcmFormat, webFormat,
            pcmData, false);
            MemoryStream ms = new MemoryStream();

            using (WaveWriter ww = new WaveWriter(ms,
            AudioCompressionManager.FormatBytes(webFormat)))
            {
                ww.WriteData(webData);
                using (WaveReader wr2 = new WaveReader(ms))
                {
                    using (FileStream fs = File.OpenWrite(webFile))
                    {
                        wr2.MakeMP3(fs);
                    }
                }
            }
        }
    }