0

I am trying to play an mp3 from an internet source while streaming in the same time. I've writen the code below and it throws the exception WaveBadFormat calling WaveOut at the player.Init() line. How should I fix this?

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);

} 
  • Might be similar to [this](http://stackoverflow.com/questions/2488426/how-to-play-a-mp3-file-using-naudio), but I'm not sure. – NaCl Nov 16 '15 at 20:49
  • I don't think the problem is same. Because in that code, the source is a file, in my project the source is an url source. I have tried to implement Mark Heath's streaming code in [here](https://naudio.codeplex.com/SourceControl/latest#NAudioDemo/Mp3StreamingDemo/MP3StreamingPanel.cs). But some problems was occured. – hasan basri Nov 16 '15 at 23:35

1 Answers1

0

the WaveFormat of your BufferedWaveProvider should be the PCM format you decompress the MP3 into, not an Mp3WaveFormat. Your WaveOut device can only play PCM.

Mark Heath
  • 48,273
  • 29
  • 137
  • 194