简体   繁体   English

从字符串到numpy.int16数组的快速转换

[英]Fast conversion from string to numpy.int16 array

I read (int)32 bit audio data (given as string by previous commands) into a numpy.int32 array with : 我读取(int)32位音频data (由先前命令以字符串形式给出)到numpy.int32数组中,其中:

myarray = numpy.fromstring(data, dtype=numpy.int32)

But then I want to store it in memory as int16 (I know this will decrease the bit depth / resolution / sound quality) : 但后来我想把它作为int16存储在内存中(我知道这会降低位深度/分辨率/音质):

myarray = myarray >> 16
my_16bit_array = myarray.astype('int16')

It works very well, but : is there a faster solution? 它工作得很好,但是:有更快的解决方案吗? (here I use : a string buffer, 1 array in int32, 1 array in int16 ; I wanted to know if it's possible to save one step) (这里我使用:字符串缓冲区,int32中的1个数组,int16中的1个数组;我想知道是否可以保存一个步骤)

How about this? 这个怎么样?

np.fromstring(data, dtype=np.uint16)[0::2]

Note however, that overhead of the kind you describe here is common when working with numpy, and cannot always be avoided. 但请注意,在使用numpy时,此处描述的类型的开销很常见,并且无法始终避免。 If this kind of overhead isn't acceptable for your application, make sure that you plan ahead to write extension modules for the performance critical parts. 如果您的应用程序无法接受此类开销,请确保提前计划为性能关键部分编写扩展模块。

Note: it should be 0::2 or 1::2 depending on the endianness of your platform 注意:它应该是0 :: 2或1 :: 2,具体取决于平台的字节顺序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM