This project has moved and is read-only. For the latest updates, please go here.

Exception: Index was outside the bounds of the array

Oct 1, 2014 at 12:37 AM
Edited Oct 1, 2014 at 5:12 PM
Good evening,

I'm trying to decrypt an audio file and load it in runtime (I can encrypt and decrypt using real files), but I'm struggling with this exception: Index was outside the bounds of the array

I currently have the following code:
           WaveStream stream;

           // (....) decrypting algorithm part 1

            MemoryStream ms = new MemoryStream();

            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);

            cs.Write(inputByteArray, 0, inputByteArray.Length);

            cs.FlushFinalBlock();

            stream = new Mp3FileReader(ms);
After searching for a while, I read something about a ConvertNonSeekableStreamToByteArray so I tried the folowing, which works:
            WaveStream stream;

            // (....) decrypting algorithm part 1

            MemoryStream ms = new MemoryStream();

            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);

            cs.Write(inputByteArray, 0, inputByteArray.Length);

            cs.FlushFinalBlock();

            // create file and write inside
            FileStream fs = File.OpenWrite("decrypted.mp3");
            foreach (byte b in ms.ToArray())
            {

                fs.WriteByte(b);

            }
Basically, I use the MemoryStream to write a file.

Then, instead of decrypting in runtime, I just load the FileStream as so:
            FileStream ffs = new FileStream("decrypted.mp3", FileMode.Open, FileAccess.Read);

            stream = new Mp3FileReader(ffs);
Basically, I load the decrypted file. It works, but it creates a real file (decrypted).
I don't want to create the file, I just need the memory (as shown in the first example).

I've read some threads about a ConvertNonSeekableStreamToByteArray method. Is it somehow related to it?

Any thoughts?

One more question. After reading the audio file successfully, I have the following code:
        stream = new WaveFormatConversionStream(new WaveFormat(44100, 1), stream);
        offset = new WaveOffsetStream(stream);
        channel = new WaveChannel32(offset);
        channel.Volume = volume;
I've read some threads saying that there's no need to use WaveFormatConversionStream. What's the best way?

Sincerely,
Apidcloud
Oct 1, 2014 at 5:21 PM
I just tried to convert the MemoryStream into a new Stream (using array of bytes) and it worked. For some reason it does work this way..
                Stream myStream = new MemoryStream(ms.ToArray());


                stream = new Mp3FileReader(myStream);
Marked as answer by Apidcloud on 10/1/2014 at 9:21 AM
Oct 2, 2014 at 5:13 PM
Glad you found a way to get it working.