Trouble converting an MP3 file to a WAV file using Naudio

Posted by WebDevHobo on Stack Overflow See other posts from Stack Overflow or by WebDevHobo
Published on 2010-05-08T17:39:58Z Indexed on 2010/05/08 17:48 UTC
Read the original article Hit count: 601

Filed under:
|
|
|

Naudio Library: http://naudio.codeplex.com/

I'm trying to convert an MP3 file to a WAV file, but I've run in to a small error. I know what's going wrong, but I don't really know how to go about fixing it.

Here's the piece of code I'm running:

private void button1_Click(object sender, EventArgs e) {
    using(Mp3FileReader reader = new Mp3FileReader(@"path\to\MP3")) {
        using(WaveFileWriter writer = new WaveFileWriter(@"C:\test.wav", new WaveFormat())) {
            int counter = 0;
            while(reader.Read(test, counter, test.Length + counter) != 0) {
                writer.WriteData(test, counter, test.Length + counter);
                counter += 512;
            }
        }
    }
}

reader.Read() goes into the Mp3FileReader class, and the method looks like this:

public override int Read(byte[] sampleBuffer, int offset, int numBytes)
{
    if (numBytes % waveFormat.BlockAlign != 0)
        //throw new ApplicationException("Must read complete blocks");
        numBytes -= (numBytes % waveFormat.BlockAlign);
    return mp3Stream.Read(sampleBuffer, offset, numBytes);
}

mp3Stream is an object of the Stream class.

The problem is: I'm getting an ArgumentException. MSDN says that this is because the sum of offset and numBytes is greater than the length of sampleBuffer.

Documentation: http://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx

This happens because I increase the counter every time, but the size of the byte array test remains the same.

What I've been wondering is: do I need to increase the size of the array dynamically, or do I need to find out the needed size at the beginning and set it right away?

And also, instead of 512, the method in Mp3FileReader returns 365 the first time. Which is the size of a whole block. But I'm writing the full 512. I'm basically just using the read to check if I'm not at the end of the file yet. Do I need to catch the return value and do something with that, or am I good here?

© Stack Overflow or respective owner

Related posts about c#

Related posts about naudio