Search code examples
pythonnumpyscipypyaudio

Play square wave SciPy and PyAudio


I'm trying to play square waves generated using SciPy with PyAudio but I get the error

TypeError: len() of unsized object

which is kind of strange because the square wave object should have a size, right?

RATE = 48000
p = pyaudio.PyAudio()
stream = p.open(format = pyaudio.paInt16,
            channels = 2,
            rate = RATE,
            output = True)
# ... inside a loop
    wav = signal.square(2*math.pi*FREQ*t)
    wav = wav.astype(np.int16)
    stream.write(wav) # crash here

The crash happens on the first iteration of the loop, so I suppose the loop is not a problem.


Solution

  • I get the same error. However, you are omitting some information, so I will assume these are your imports:

    import pyaudio
    import math
    import numpy as np
    from scipy import signal
    

    And that

    FREQ = 440
    

    It looks like the variable you are iterating is t and it's a scalar. You might have good reasons to do this, but I don't think it is how scipy.signal is meant to work. If you use a vector t instead:

    t = np.linspace(0, 2)
    

    Then signal.square(...) and stream.write(wav.astype(np.int16)) work without problems.