简体   繁体   中英

Convert list of floats into buffer in Python?

I am playing around with PortAudio and 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:

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:

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 . It is designed to convert from python objects to C-like "native" objects.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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