[英]How have a generic conversion from 32/24bit From Bytes To 16bit To bytes
Have been searching the solution for two days. 已经搜索解决方案两天了。 I want to convert my wave 32 or 24 bits to a 16bit.
我想将wave的32位或24位转换为16位。
This my code after reading few stackoverflow topics): 阅读了几个stackoverflow主题后,这是我的代码):
byte[] data = Convert.FromBase64String("-- Wav String encoded --") (32 or 24 bits)
int conv = Convert.ToInt16(data);
byte[] intBytes = BitConverter.GetBytes(conv);
if (BitConverter.IsLittleEndian)
Array.Reverse(intBytes);
byte[] result = intBytes;
but when i writeAllbyte my result, nothing to hear... 但是当我writeAllbyte我的结果时,什么也听不到...
Here is a method that cuts the least significant bits: 这是一种削减最低有效位的方法:
byte[] data = ...
var skipBytes = 0;
byte[] data16bit;
int samples;
if( /* data was 32 bit */ ) {
skipBytes = 2;
samples = data.Length / 4;
} else if( /* data was 24 bit */ ) {
skipBytes = 1;
samples = data.Length / 3;
}
data16bit = new byte[samples * 2];
int writeIndex = 0;
int readIndex = 0;
for(var i = 0; i < samples; ++i) {
readIndex += skipBytes; //skip the least significant bytes
//read the two most significant bytes
data16bit[writeIndex++] = data[readIndex++];
data16bit[writeIndex++] = data[readIndex++];
}
This assumes a little endian byte order (least significant byte is the first byte, usual for WAV RIFF). 假定字节顺序为小字节(最低有效字节为第一个字节,通常用于WAV RIFF)。 If you have big endian, you have to put the
readIndex += ...
after the two read lines. 如果您有大字节序,则必须在两行读取之后放置
readIndex += ...
You could implement your own conversion iterator for this task like so: 您可以为该任务实现自己的转换迭代器,如下所示:
IEnumerable<byte> ConvertTo16Bit(byte[] data, int skipBytes)
{
int bytesToRead = 0;
int bytesToSkip = skipBytes;
int readIndex = 0;
while (readIndex < data.Length)
{
if (bytesToSkip > 0)
{
readIndex += bytesToSkip;
bytesToSkip = 0;
bytesToRead = 2;
continue;
}
if (bytesToRead == 0)
{
bytesToSkip = skipBytes;
continue;
}
yield return data[readIndex++];
bytesToRead--;
}
}
This way you don't have to create a new array if there is no need for it. 这样,您就不需要创建新数组。 And you could simply convert the data array to a new 16 bit array with the
IEnumerable<T>
extension methods: 您可以使用
IEnumerable<T>
扩展方法将数据数组简单地转换为新的16位数组:
var data16bit = ConvertTo16Bit(data, 1).ToArray();
Or if you don't need the array, you can iterate the data skipping the least significant bytes: 或者,如果不需要数组,可以跳过最低有效字节来迭代数据:
foreach (var b in ConvertTo16Bit(data, 1))
{
Console.WriteLine(b);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.