简体   繁体   English

在Python中将浮点数列表转换为缓冲区?

[英]Convert list of floats into buffer in Python?

I am playing around with PortAudio and Python. 我正在玩PortAudio和Python。

data = getData()
stream.write( data )

I want my stream to play sound data, that is represented in Float32 values. 我希望我的流播放声音数据,用Float32值表示。 Therefore I use the following function: 因此我使用以下功能:

def getData():
    data = []
    for i in range( 0, 1024 ):
        data.append( 0.25 * math.sin( math.radians( i ) ) )
    return data

Unfortunately that doesn't work because stream.write wants a buffer object to be passed in: 不幸的是,这不起作用,因为stream.write想要传入缓冲区对象:

TypeError: argument 2 must be string or read-only buffer, not list

So my question is: How can I convert my list of floats in to a buffer object? 所以我的问题是:如何将我的浮动列表转换为缓冲区对象?

import struct

def getData():
    data = []
    for i in range( 0, 1024 ):
        data.append( 0.25 * math.sin( math.radians( i ) ) )
    return struct.pack('f'*len(data), *data)

Actually, the easiest way is to use the struct module . 实际上,最简单的方法是使用struct模块 It is designed to convert from python objects to C-like "native" objects. 它旨在从python对象转换为类似C的“本机”对象。

Consider perhaps instead: 或许考虑一下:

d = [0.25 * math.sin(math.radians(i)) for i in range(0, 1024)]

Perhaps you have to use a package like pickle to serialize the data first. 也许您必须首先使用像pickle这样的包来序列化数据。

import pickle
f1 = open("test.dat", "wb")
pickle.dump(d, f1)
f1.close()

Then load it back in: 然后将其加载回:

f2 = open("test.dat", "rb")
d2 = pickle.Unpickler(f2).load()
f2.close()


d2 == d

Returns True 返回True

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

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