This project has moved. For the latest updates, please go here.

Playing an MP3 file using BufferedWaveProvider

Oct 17, 2010 at 2:18 AM

Hi,

I just started using NAudio - it is really great.

I'm trying to read an MP3 file into memory as a whole buffer, perform some dynamic (UI driven) processing in a loop and then let BufferedWaveProvider play it.

My plan is to use BufferedWaveProvider queuing mechanism and to add samples to the queue on the fly.

The MP3 I'm using is 44000, 32 bit, 2 channel.

This is my test code - It compiles and runs but sounds terrible - very noisy. I guess it is due to some format conversion, but not sure what exactly. Maybe the float to byte conversion?

        private IWaveProvider CreateBufferedWaveProvider(string filename)
        {
            WaveStream mp3Reader = new Mp3FileReader(filename);
            WaveStream pcmStream = WaveFormatConversionStream.CreatePcmStream(mp3Reader);
            WaveStream blockAlignedStream = new BlockAlignReductionStream(pcmStream);WaveChannel32 waveChannel = new WaveChannel32(blockAlignedStream);

            WaveFormat format = new WaveFormat(waveChannel.WaveFormat.SampleRate, waveChannel.WaveFormat.BitsPerSample, waveChannel.WaveFormat.Channels);
            BufferedWaveProvider inputProvider = new BufferedWaveProvider(format);

            byte[] buffer1 = new byte[waveChannel.WaveFormat.SampleRate];
            int bytesRead;

            for (int i = 0; i < 100; i++)
            {
                bytesRead = waveChannel.Read(buffer1, 0, waveChannel.WaveFormat.SampleRate);
                inputProvider.AddSamples(buffer1, 0, bytesRead );
            }

            waveChannel.Dispose();
            blockAlignedStream.Dispose();
            pcmStream.Dispose();
            mp3Reader.Dispose();

            return inputProvider;
        }

Thanks,

Yuval

Oct 17, 2010 at 10:49 AM

I'm not very acquainted with the BufferedWaveProvider, but it might be due to the latency of whatever IWavePlayer you are using, if you are even using one. If I set it too low, I get playback like that.

Oct 17, 2010 at 1:59 PM

Thanks for trying to help!

Well, it wasn't the latency but I found the problem:

It was the float to byte conversion after all - I created a wave format that was not IeeeFloat but the actual data was.

So I changed these rows:

    WaveFormat format = new WaveFormat(waveChannel.WaveFormat.SampleRate, waveChannel.WaveFormat.BitsPerSample, waveChannel.WaveFormat.Channels); 
    BufferedWaveProvider inputProvider = new BufferedWaveProvider(format);

into this row: (The wave format is simply passed from the channel)
    BufferedWaveProvider inputProvider = new BufferedWaveProvider(waveChannel.WaveFormat);

And now it works fine.

Thanks,
Yuval