File Encode and Decode example

Dec 26, 2011 at 6:24 PM
Edited Dec 26, 2011 at 11:20 PM

There have been several Encode and Decode discussions here so far. I have looked through and none have the resulting code that works. 

Can someone please show how to Encode a PCM data array and save it to a file, and then read it and decode it correctly. 

Thank you very much in advance.

Dec 3, 2012 at 10:07 PM

*bump*

Anyone? 

Jan 11, 2013 at 5:20 PM

 

I check out the latest source code and compile it.  bellow method can encode pcm data correctly

and I save output stream to spx file which can be played by foobar2000.

I hope this will help

// Desired format is 8kHz 16bit mono

 public static void SaveToSpeex(Stream input, Stream output, AudioFormat audioFormat)

        {

            if (audioFormat.WaveFormat != WaveFormatType.Pcm)

                throw new ArgumentException("Only PCM coding is supported.");

 

 

            byte[] rawData = ((MemoryStream)input).ToArray();

 

            var encoder = new SpeexEncoder(BandMode.Narrow);

            var oggWriter = new OggSpeexWriter(0, encoder.SampleRate, 1, 1, encoder.VBR);

 

            var inDataSize = rawData.Length / 2;

            inDataSize = inDataSize - inDataSize % encoder.FrameSize;

            var inData = new short[inDataSize];

 

            for (var index = 0; index < inDataSize; index++)

            {

                inData[index] = BitConverter.ToInt16(rawData, index * 2);

            }

 

 

            oggWriter.Open(output);

            oggWriter.WriteHeader("spx test");

 

            var encodingFrameSize = encoder.FrameSize;

            var encodedBuffer = new byte[1024];

            for (var offset = 0; offset + encodingFrameSize < inDataSize; offset += encodingFrameSize)

            {

                var encodedBytes = encoder.Encode(inData, offset, encodingFrameSize, encodedBuffer, 0, encodingFrameSize);

                var encodedFrame = new byte[encodedBytes];

                Array.Copy(encodedBuffer, 0, encodedFrame, 0, encodedBytes);

 

 

 

                oggWriter.WritePacket(encodedFrame, 0, encodedFrame.Length);

            }

 

            oggWriter.Close();  

        }

Oct 14, 2014 at 9:45 PM
Edited Oct 14, 2014 at 9:45 PM
flagaemonster,

Could you also share decode part, read spx input, and convert it to PCM?

I looked everywhere, but didn't see a class like OggSpeexReader. Is there a way to read spx streams?

Thanks
Apr 19, 2015 at 3:04 PM
I really need this too.