connecting embedded Python audio samples with NumPy?

Fernando Pérez fperez528 at yahoo.com
Thu Jun 27 14:44:23 EDT 2002


Paul Miller wrote:

> I have a C app that reads audio data, and I'd like to pass this audio
> data in array format to Python functions so I can use it with NumPy.
> 
> I have this working right now - generating a float array from the sample
> stream. But I want to put this array into a form usable by the FFT
> functions. I've read over this paper:
> 
> http://www.onlamp.com/pub/a/python/2001/01/31/numerically.html
> 
> Which indicates I need to put my 1D sample stream into a 2D array. Can
> anyone elaborate more on this? I'm wondering if I should provide the
> array pre-made for FFTs from my C code, or I should build the 2D array
> from the 1D array I have in Python.

I don't see why you need to convert the data stream to a 2d array. In fact, 
since you know your data is real, you can use FFT.real_fft() and 
FFT.inverse_real_fft() for the conversions, which guarantees that after 
processing you get real data back (without coefficients with small imaginary 
parts). That is, of course, as long as in your processing you don't break the 
symmetry assumptions on the fft data for a real signal :)

FFT comes with Numeric, so with a properly installed numeric it imports 
straight out. Here's a quick example:

In [1]: x = frange(0,2*pi,npts=8)

In [2]: y = sin(x) + sin(4*x)

In [3]: import FFT

In [4]: yhat = FFT.real_fft(y)

In [5]: yhat
Out[5]:
array([ -6.66133815e-16+0.j        ,   1.32978452e+00-3.21038382j,
             -8.67767478e-01+0.86776748j,  -2.41187287e+00+0.99903045j,
              3.89971165e+00+0.j        ])

In [6]: y2 = FFT.inverse_real_fft(yhat)

In [7]: y2
Out[7]:
array([ -5.55111512e-17,   3.47947743e-01,   1.75675939e+00,  -5.41044173e-01,
              5.41044173e-01,  -1.75675939e+00,  -3.47947743e-01,  
-1.27675648e-15])

In [8]: y2 - y
Out[8]:
array([ -5.55111512e-17,  -5.55111512e-17,   2.22044605e-16,   0.00000000e+00,
              0.00000000e+00,   0.00000000e+00,  -5.55111512e-17,  
-5.21501245e-17])

So within the accuracy of a C double, it all works as expected.

Cheers,

f




More information about the Python-list mailing list