我试图使用XNA麦克风捕捉音频,并将其传递给我所拥有的API,该API将分析数据以供显示。然而,API需要16位整数数组中的音频数据。因此,我的问题相当直截了当;将字节数组转换为短数组的最有效方法是什么?
private void _microphone_BufferReady(object sender, System.EventArgs e)
{
_microphone.GetData(_buffer);
short[] shorts;
//Convert and pass the 16 bit samples
ProcessData(shorts);
}干杯,戴夫
编辑:这就是我想出来的,而且看起来很有效,但是它能更快地完成吗?
private short[] ConvertBytesToShorts(byte[] bytesBuffer)
{
//Shorts array should be half the size of the bytes buffer, as each short represents 2 bytes (16bits)
short[] shorts = new short[bytesBuffer.Length / 2];
int currentStartIndex = 0;
for (int i = 0; i < shorts.Length - 1; i++)
{
//Convert the 2 bytes at the currentStartIndex to a short
shorts[i] = BitConverter.ToInt16(bytesBuffer, currentStartIndex);
//increment by 2, ready to combine the next 2 bytes in the buffer
currentStartIndex += 2;
}
return shorts;
}发布于 2011-04-20 14:20:04
在阅读您的更新之后,我可以看到您实际上需要将一个字节数组直接复制到一个简短的缓冲区中,合并字节。这是文档的相关部分
byte[]缓冲区格式用作SoundEffect构造函数、Microphone.GetData方法和DynamicSoundEffectInstance.SubmitBuffer方法的参数,是PCM波形数据。此外,PCM格式是交错的和小终端.
现在,如果由于某种奇怪的原因,您的系统有BitConverter.IsLittleEndian == false,那么您将需要遍历缓冲区,在执行过程中交换字节,以便从小端到大端点转换。我将把代码作为练习--我相当肯定所有的XNA系统都是小端的。
出于您的目的,您可以直接使用Marshal.Copy或Buffer.BlockCopy复制缓冲区。这两种操作都将为您提供平台的本机内存复制操作的性能,该操作将非常快:
// Create this buffer once and reuse it! Don't recreate it each time!
short[] shorts = new short[_buffer.Length/2];
// Option one:
unsafe
{
fixed(short* pShorts = shorts)
Marshal.Copy(_buffer, 0, (IntPtr)pShorts, _buffer.Length);
}
// Option two:
Buffer.BlockCopy(_buffer, 0, shorts, 0, _buffer.Length);发布于 2011-04-20 14:04:45
我能想到的害虫是在这里。
private short[] ConvertBytesToShorts(byte[] bytesBuffer)
{
//Shorts array should be half the size of the bytes buffer, as each short represents 2 bytes (16bits)
var odd = buffer.AsParallel().Where((b, i) => i % 2 != 0);
var even = buffer.AsParallell().Where((b, i) => i % 2 == 0);
return odd.Zip(even, (o, e) => {
return (short)((o << 8) | e);
}.ToArray();
}我对性能很怀疑,但是有足够的数据和处理器,谁知道呢。
如果转换操作错误((short)((o << 8) | e)),请更改以适应。
https://stackoverflow.com/questions/5728865
复制相似问题