将通过HTTP流式传输的wav实时转换为mp3

时间:2014-06-13 16:53:23

标签: c# .net http naudio lame

后台:我正在使用返回MIME类型为audio/wav的数据的服务。我需要为这个音频提供一个播放机制(目前作为MVC应用程序构建)。例如,我的端点看起来像https://audio.fooservice.com/GetAudio?audioId=123

音频为8kHz,1通道u-law。

由于使用HTML5 <audio>标记时浏览器的格式支持不同,我无法使用原始的u-law wav,因为Internet Explorer无法播放它。

我建议的解决方案是从源格式到mp3进行实时转换。

我已经在这里和 NAudio 论坛中拼凑出了来自其他各种问题的部分工作解决方案,但它引发了一个例外,如下面的评论中所述:

private void NAudioTest(string url)
{
    Stream outStream = new MemoryStream();
    var format = WaveFormat.CreateMuLawFormat(8000, 1);

    using (Stream ms = new MemoryStream())
    {
        var request = (HttpWebRequest)WebRequest.Create(url);
        request.KeepAlive = false;
        request.ProtocolVersion = HttpVersion.Version10;

        using (Stream stream = request.GetResponse().GetResponseStream())
        {
            using (var reader = new RawSourceWaveStream(stream, format))
            {
                // reader is not seekable; we need to convert to a byte array to seek
                var bytes = reader.ToByteArray();

                // create a new stream from the byte aray
                var seekableStream = new MemoryStream(bytes);

                // instantiating a WaveFileReader as follows will throw an exception:
                // "System.FormatException: Not a WAVE file - no RIFF header"
                using (var waveReader = new WaveFileReader(seekableStream))
                {
                    using (var pcmStream = WaveFormatConversionStream.CreatePcmStream(waveReader))
                    {
                        var pcmBytes = pcmStream.ToByteArray();
                        var mp3 = pcmBytes.ToMp3();
                    }
                }
            }
        }
    }
}

public static class StreamExtensions
{
    public static byte[] ToByteArray(this Stream stream)
    {
        var ms = new MemoryStream();
        var buffer = new byte[1024];
        int bytes = 0;

        while ((bytes = stream.Read(buffer, 0, buffer.Length)) > 0)
            ms.Write(buffer, 0, bytes);

        return ms.ToArray();
    }
}

public static class ByteExtensions
{
    public static byte[] ToMp3(this byte[] bytes)
    {
        using (var outStream = new MemoryStream())
        {
            using (var ms = new MemoryStream(bytes))
            {
                using (var reader = new WaveFileReader(ms))
                {
                    using (var writer = new LameMP3FileWriter(outStream, reader.WaveFormat, 64))
                    {
                        reader.CopyTo(writer);
                        return outStream.ToArray();
                    }
                }
            }
        }
    }
}

我在这一天的大部分时间里一直在探索这个问题,我觉得我将不必要的复杂性引入了似乎的东西,就像它应该相当简单。

非常感谢任何帮助。

注意:我无法更改源格式,支持IE是必需的。

编辑:我解决了RIFF异常,并且能够制作MP3的流,但它只是白噪声。希望我也可以解决这个问题。我的新代码如下:

[HttpGet]
public ActionResult GetMp3(string url)
{
    if (String.IsNullOrWhiteSpace(url))
        return null;

    var muLawFormat = WaveFormat.CreateMuLawFormat(8000, 1);
    var compressedStream = new MemoryStream();

    using (var ms = new MemoryStream())
    {
        var request = (HttpWebRequest)WebRequest.Create(url);
        request.KeepAlive = false;
        request.ProtocolVersion = HttpVersion.Version10;

        using (Stream webStream = request.GetResponse().GetResponseStream())
        {
            var buffer = new byte[4096];
            int read;
            while (webStream != null && (read = webStream.Read(buffer, 0, buffer.Length)) > 0)
                ms.Write(buffer, 0, read);
        }

        ms.Position = 0;

        using (WaveStream wav = WaveFormatConversionStream.CreatePcmStream(new RawSourceWaveStream(ms, muLawFormat)))
        using (var mp3 = new LameMP3FileWriter(compressedStream, new WaveFormat(), LAMEPreset.MEDIUM_FAST))
            wav.CopyTo(mp3);
    }

    compressedStream.Seek(0, 0);
    return new FileStreamResult(compressedStream, "audio/mpeg");
}

1 个答案:

答案 0 :(得分:0)

这适合我(我需要做你想做的事)。希望这也有助于其他人。我使用了带有LAME的NAudio。

您必须确保将libmp3lamexx.dll文件复制到网络服务器的BIN位置或%PATH%变量中的某个文件夹,否则它将无法正常工作。

        string sq = /* URL of WAV file (http://foo.com/blah.wav) */

        Response.ContentType = "audio/mpeg";

        using (WebClient wc = new WebClient())
        {
            if (!sq.ToLower().EndsWith(".wav"))
            {
                byte[] rawFile = wc.DownloadData(sq.Trim());
                Response.OutputStream.Write(rawFile, 0, rawFile.Length);
            }
            else
            {
                using (var wavReader = new WaveFileReader(new MemoryStream(wc.DownloadData(sq.Trim()))))
                {
                    try
                    {
                        using (var wavWriter = new LameMP3FileWriter(Response.OutputStream, wavReader.WaveFormat, LAMEPreset.ABR_128))
                        {
                            wavReader.CopyTo(wavWriter);
                        }
                    }
                    catch (ArgumentException)
                    {
                        var newFormat = new WaveFormat(wavReader.WaveFormat.SampleRate, 16, 2);

                        using (var pcmStream = new WaveFormatConversionStream(newFormat, wavReader))
                        {
                            using (var wavWriter = new LameMP3FileWriter(Response.OutputStream, pcmStream.WaveFormat, LAMEPreset.ABR_128))
                            {
                                pcmStream.CopyTo(wavWriter);
                            }
                        }
                    }
                }
            }

            Response.Flush();
            Response.End();
        }