首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >高效地将音频字节- byte[]转换为short[]

高效地将音频字节- byte[]转换为short[]
EN

Stack Overflow用户
提问于 2011-04-20 10:29:12
回答 2查看 2.8K关注 0票数 2

我试图使用XNA麦克风捕捉音频,并将其传递给我所拥有的API,该API将分析数据以供显示。然而,API需要16位整数数组中的音频数据。因此,我的问题相当直截了当;将字节数组转换为短数组的最有效方法是什么?

代码语言:javascript
复制
    private void _microphone_BufferReady(object sender, System.EventArgs e)
    {
        _microphone.GetData(_buffer);

        short[] shorts;

        //Convert and pass the 16 bit samples
        ProcessData(shorts);
    }

干杯,戴夫

编辑:这就是我想出来的,而且看起来很有效,但是它能更快地完成吗?

代码语言:javascript
复制
    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;

    }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-04-20 14:20:04

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

byte[]缓冲区格式用作SoundEffect构造函数、Microphone.GetData方法和DynamicSoundEffectInstance.SubmitBuffer方法的参数,是PCM波形数据。此外,PCM格式是交错的和小终端.

现在,如果由于某种奇怪的原因,您的系统有BitConverter.IsLittleEndian == false,那么您将需要遍历缓冲区,在执行过程中交换字节,以便从小端到大端点转换。我将把代码作为练习--我相当肯定所有的XNA系统都是小端的。

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

代码语言:javascript
复制
// 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);
票数 5
EN

Stack Overflow用户

发布于 2011-04-20 14:04:45

我能想到的害虫是在这里。

代码语言:javascript
复制
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)),请更改以适应。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5728865

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档