I need fastest way to convert byte array to short array of audio data.
Audio data byte array contains data from two audio channels placed in such way:
C1C1C2C2 C1C1C2C2 C1C1C2C2 ...
where
C1C1 - two bytes of first channel
C2C2 - two bytes of second channel
Currently I use such algorithm, but I feel there is better way to perform this task.
byte[] rawData = //from audio device
short[] shorts = new short[rawData.Length / 2];
short[] channel1 = new short[rawData.Length / 4];
short[] channel2 = new short[rawData.Length / 4];
System.Buffer.BlockCopy(rawData, 0, shorts, 0, rawData.Length);
for (int i = 0, j = 0; i < shorts.Length; i+=2, ++j)
{
channel1[j] = shorts[i];
channel2[j] = shorts[i+1];
}
You could use unsafe code to avoid array addressing or bit shifts. But as PVitt said on new PCs you are better using standard managed code and the TPL if your data size is important.
As with all optimization problems you need to time carefully, pay special attention to your
buffer allocations, channel1 and channel2 could be static (big) buffers growing automatically
and you could use only the nth first bytes. You will be able to skip 2 big arrays allocations
for each executions of this function. and will make the GC work less
(always better when timing is important)
As noted by CodeInChaos the endianness could be important, if your data is not in the
correct endianness you will need to do the conversion, for example to convert between big
and little endian assuming 8bit atomic elements the code will look like :
I didn’t compile any code in this post with an actual compiler so if you find errors feel free to edit it.