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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1229202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:44:22  来源:igfitidea点击:

Convert list of floats into buffer in Python?

pythonlistfloating-pointbuffer

提问by okoman

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. Therefore I use the following function:

我希望我的流播放声音数据,以 Float32 值表示。因此我使用以下功能:

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.writewants 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?

所以我的问题是:如何将我的浮点数列表转换为缓冲区对象?

回答by Unknown

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)

回答by Christopher

Actually, the easiest way is to use the struct module. It is designed to convert from python objects to C-like "native" objects.

实际上,最简单的方法是使用struct 模块。它旨在从 python 对象转换为类似 C 的“本机”对象。

回答by Brian R. Bondy

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

返回真