gpt4 book ai didi

c# - 高效地将音频字节 - byte[] 转换为 Short[]

转载 作者:行者123 更新时间:2023-12-03 19:30:18 26 4
gpt4 key购买 nike

我正在尝试使用 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;

}

最佳答案

阅读您的更新后,我可以看到您实际上需要将字节数组直接复制到短裤缓冲区中,合并字节。这是 documentation 中的相关部分:

The byte[] buffer format used as a parameter for the SoundEffect constructor, Microphone.GetData method, and DynamicSoundEffectInstance.SubmitBuffer method is PCM wave data. Additionally, the PCM format is interleaved and in little-endian.

现在,如果由于某种奇怪的原因你的系统有BitConverter.IsLittleEndian == false,那么你将需要循环遍历你的缓冲区,交换字节,从小端转换为大尾数。我将把代码留作练习 - 我有理由确信所有 XNA 系统都是小尾数法。

出于您的目的,您可以直接使用 Marshal.CopyBuffer.BlockCopy 复制缓冲区。两者都将为您提供平台 native 内存复制操作的性能,这将非常快:

// 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);

关于c# - 高效地将音频字节 - byte[] 转换为 Short[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5728865/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com