如何正确地将16Bit字节数组转换为音频片段数据? [英] How to convert 16Bit byte array to audio clip data correctly?
问题描述
我与Media Foundataion合作,我需要做的是将声音样本帧从字节转换为音频浮动数据.为了做到这一点,我使用了这种方法(我在Google的某个地方找到了它):
I work with Media Foundataion and what I need to do is convert sound sample frame from byte to audio float data. In order to do it I use such method (that I found somewhere at google):
private static float[] Convert16BitByteArrayToAudioClipData(byte[] source, int headerOffset, int dataSize)
{
int wavSize = BitConverter.ToInt32(source, headerOffset);
headerOffset += sizeof(int);
Debug.AssertFormat(wavSize > 0 && wavSize == dataSize, "Failed to get valid 16-bit wav size: {0} from data bytes: {1} at offset: {2}", wavSize, dataSize, headerOffset);
int x = sizeof(Int16); // block size = 2
int convertedSize = wavSize / x;
float[] data = new float[convertedSize];
Int16 maxValue = Int16.MaxValue;
int i = 0;
while (i < convertedSize)
{
int offset = i * x + headerOffset;
data[i] = (float)BitConverter.ToInt16(source, offset) / maxValue;
++i;
}
Debug.AssertFormat(data.Length == convertedSize, "AudioClip .wav data is wrong size: {0} == {1}", data.Length, convertedSize);
return data;
}
我这样使用它:
...
byte[] source = ...; // lenght 43776
... = Convert16BitByteArrayToAudioClipData(source , 0, 0);
...
这种方法的工作方式似乎是错误的,因为如果我在索引 i = 21886
的 while
循环中传递大小为43776的数组,则偏移值将为 offset = 43776
会导致下一个方法出现异常
Looks like this method works wrong, because if I pass an array with size 43776 as a result in while
loop at index i = 21886
offset value will be offset = 43776
it lead to exception at this next method
data[i] = (float)BitConverter.ToInt16(source /*43776*/, offset /*43776*/) / maxValue;
因为此值不能相同.
问题是-如何解决此方法?也许有人可以建议使用什么替代方法?
Question is - how to fix this method? Or maybe someone can advice what to use instead?
编辑
private static float[] Convert16BitByteArrayToAudioClipData(byte[] source)
{
float[] data = new float[source.Length];
for (int i = 0; i < source.Length; i++)
{
data[i] = (float) source[i];
}
return data;
}
推荐答案
最终我是这样做的:
public static float[] Convert16BitByteArrayToAudioClipData(byte[] source)
{
int x = sizeof(Int16);
int convertedSize = source.Length / x;
float[] data = new float[convertedSize];
Int16 maxValue = Int16.MaxValue;
for (int i = 0; i < convertedSize; i++)
{
int offset = i * x;
data[i] = (float)BitConverter.ToInt16(source, offset) / maxValue;
++i;
}
return data;
}
这篇关于如何正确地将16Bit字节数组转换为音频片段数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!