尝试流式播放时,NAudio WaveBadFormat异常

时间:2015-11-16 18:05:05

标签: c#-4.0 naudio

我正在尝试在同时播放流媒体时播放mp3。我已经编写了下面的代码,它会在WaveBadFormat calling WaveOut行抛出异常player.Init()。我该如何解决这个问题?

string testLink = "http://users.skynet.be/fa046054/home/P22/track49.mp3";

req = WebRequest.Create(testLink) as HttpWebRequest;
resp = req.GetResponse() as HttpWebResponse;
str = resp.GetResponseStream();

int readBytes = 0;
int totalBytes = 0;
byte[] buffer = new byte[1024];
byte[] mp3Buffer = new byte[45000];

IMp3FrameDecompressor decompressor = null;
BufferedWaveProvider provider = null;
WaveOut player = new WaveOut();
Mp3Frame frame = Mp3Frame.LoadFromStream(new ReadFullyStream(str));

while ((readBytes = str.Read(buffer, 0, buffer.Length)) > 0)
{
    totalBytes += readBytes;
    if (decompressor == null && totalBytes > 1024) 
    {
        Mp3WaveFormat format = new Mp3WaveFormat(frame.SampleRate,
                    frame.ChannelMode == ChannelMode.Mono ? 1 : 2,
                    frame.FrameLength, frame.BitRate);
        decompressor = new AcmMp3FrameDecompressor(format);

        provider = new BufferedWaveProvider(format);
        int x = decompressor.DecompressFrame(frame, mp3Buffer, 0);
        provider.AddSamples(mp3Buffer, 0, x);
        player.Init(provider);
        player.Play();
        continue;
    }
    Application.DoEvents();
    if (decompressor == null)
        continue;
    int decNum = decompressor.DecompressFrame(frame, mp3Buffer, 0);
    provider.AddSamples(mp3Buffer, 0, decNum);

} 

0 个答案:

没有答案