Audio playing at twice the speed

Oct 20, 2011 at 7:49 PM

It appears that when I play the decoded bytes the audio is being played twice as fast.

 

Encode:

        JSpeexEnc encoder = new JSpeexEnc();
        int rawDataSize = 0;
        public byte[] EncodeAudio(byte[] rawData)
        {
            var encoder = new SpeexEncoder(BandMode.Narrow);
            var inDataSize = rawData.Length / 2;
            var inData = new short[inDataSize];

            for (var index = 0; index < rawData.Length; index += 2)
            {
                inData[index / 2] = BitConverter.ToInt16(rawData, index);
            }
            inDataSize = inDataSize - inDataSize % encoder.FrameSize;

            var encodedData = new byte[rawData.Length];
            var encodedBytes = encoder.Encode(inData, 0, inDataSize, encodedData, 0, encodedData.Length);

            byte[] encodedAudioData = null;
            if (encodedBytes != 0)
            {
                encodedAudioData = new byte[encodedBytes];
                Array.Copy(encodedData, 0, encodedAudioData, 0, encodedBytes);
            }
            rawDataSize = inDataSize; // Count of encoded shorts, for debugging
            return encodedAudioData;
        }

Decode:

 	SpeexDecoder decoder = new SpeexDecoder(BandMode.Narrow);
        public void Decode(byte[] encodedData)
        {
            try
            {
                short[] decodedFrame = new short[8000]; // should be the same number of samples as on the capturing side
                int decoderBytes = decoder.Decode(encodedData, 0, encodedData.Length, decodedFrame, 0, false);

                byte[] decodedData = new byte[encodedData.Length];
                byte[] decodedAudioData = null;

                decodedAudioData = new byte[decoderBytes * 2];
                for (int shortIndex = 0, byteIndex = 0; byteIndex < decoderBytes; shortIndex++)
                {
                    BitConverter.GetBytes(decodedFrame[shortIndex + byteIndex]).CopyTo(decodedAudioData, byteIndex * 2);
                    byteIndex++;
                }

                // todo: do something with the decoded data
                PlayWave(decodedAudioData);
            }
            catch (Exception ex)
            {
                ShowMessageBox(ex.Message.ToString());
                return null;
            }

        }

Playing the audio:

        void PlayWave(byte[] PCMBytes)
        {
            byte[] decodedBuffer = Decode(PCMBytes);
            MemoryStream ms_PCM = new MemoryStream(decodedBuffer);
            MemoryStream ms_Wave = new MemoryStream();

            _pcm.SavePcmToWav(ms_PCM, ms_Wave, 16, 8000, 1);

            WaveMediaStreamSource WaveStream = new WaveMediaStreamSource(ms_Wave);
            mediaElement1.SetSource(WaveStream);
            mediaElement1.Play();
        }