Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 900
okoman Avatar asked Aug 04 '09 18:08

okoman


2 Answers

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)
like image 66
Unknown Avatar answered Oct 08 '22 16:10

Unknown


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

like image 27
Christopher Avatar answered Oct 08 '22 16:10

Christopher