I want to change the bit depth from 16 bits to 8 bits. Here is the conversion code from 32 bit to 16 bit:
var audioBuffer = frame.LockBuffer(AudioBufferAccessMode.Read); var buffer = Windows.Storage.Streams.Buffer.CreateCopyFromMemoryBuffer(audioBuffer); buffer.Length = audioBuffer.Length; using (var dataReader = DataReader.FromBuffer(buffer)) { dataReader.ByteOrder = ByteOrder.LittleEndian; byte[] byteData = new byte[buffer.Length / (4 * 3)]; int pos = 0; Int16 int16Tmp1; Int16 int16Tmp2; Int16 avg = 0; while (dataReader.UnconsumedBufferLength > 0) { for (int i = 0; i < 3; i++) { int16Tmp1 = (Int16)((dataReader.ReadSingle() * Int16.MaxValue) / 2); int16Tmp2 = (Int16)((dataReader.ReadSingle() * Int16.MaxValue) / 2); avg += (Int16)(int16Tmp1 + int16Tmp2); } avg = (Int16)(avg / 3); byte[] chunkBytes = BitConverter.GetBytes(avg); byteData[pos++] = chunkBytes[0]; byteData[pos++] = chunkBytes[1]; } _audioStream.Write(byteData, 0, byteData.Length); }
Here is an attempt to convert from 32 bit to 8 bit:
dataReader.ByteOrder = ByteOrder.LittleEndian; byte[] byteData = new byte[buffer.Length / (4 * 3 * 2)]; int pos = 0; sbyte int8Tmp1; sbyte int8Tmp2; sbyte avg = 0; while (dataReader.UnconsumedBufferLength > 0) { for (int i = 0; i < 3; i++) { int8Tmp1 = (sbyte)((dataReader.ReadSingle() * sbyte.MaxValue) / 2); int8Tmp2 = (sbyte)((dataReader.ReadSingle() * sbyte.MaxValue) / 2); avg += (sbyte)(int8Tmp1 + int8Tmp2); } avg = (sbyte)(avg / 3); byte[] chunkBytes = BitConverter.GetBytes(avg); byteData[pos++] = (byte)(avg); //byteData[pos++] = chunkBytes[0]; //byteData[pos++] = chunkBytes[1]; }
DataReader
reads audio frame:
- stereo.
- 32 bit
- 48 kHz
I will convert it to mono with 16 bit and 16 kHz. Well, I at least hope that is correct.
So, what do I need to change to get 8 bit sound?