Search code examples
pythonaudiopyaudiosample-rate

Why does not program cost 1 sec when it plays 44100 samples with 44100 sample rate by using PyAudio?


import pyaudio
import numpy as np
import time

RATE=44100
pa = pyaudio.PyAudio()
stream = pa.open(format=pyaudio.paFloat32,
                                channels=1,
                                rate=RATE,
                                output=True)
t = time.time()
output = np.ones(44100)*100
stream.write(output)
print(time.time()-t)

This is a test code. With 44100 sample rate, when playing 44100 samples, the time cost should be 1s. However, the output is not. Why does it happen? I am looking forward to someone's answer. Thank you very much.


Solution

  • Disclaimer: untested, just looked into the API.

    stream.write() expects a string of a defined format (here: 32bit-floatingpoint). But you pass a handle to a numpy array. PyAudio (probably) defaults to convert the passed value into a string. The string representation of your output without further modification is:

    array([ 100.,  100.,  100., ...,  100.,  100.,  100.])
    

    or 42 bytes or 2.3ms playtime.

    Try stream.write('\0\0\0\0'*44100). To use np.ones() or numpy-arrays in general you have to use the correct datatype (you defined the format to be paFloat32):

    output = np.ones(44100, dtype=np.float32).tobytes()