Search code examples
pythonaudiopyaudio

pyaudio change the number of samples of calling the callback function


I want to do a simple realtime processing to audio every 4096 samples. But this code calls the callback function every 1024 samples. I just want to change the frame_count to 4096.

import pyaudio
import time

WIDTH = 2
CHANNELS = 1
RATE = 44100

p = pyaudio.PyAudio()

def callback(in_data, frame_count, time_info, status):
    out=do_something(in_data)
    print(frame_count)#1024
    return (out, pyaudio.paContinue)

stream = p.open(format=p.get_format_from_width(WIDTH),
                channels=CHANNELS,
                rate=RATE,
                input=True,
                output=True,
                stream_callback=callback)

stream.start_stream()

while stream.is_active():
    time.sleep(0.1)

stream.stop_stream()
stream.close()

p.terminate()

Solution

  • I haven't tested it, but from the documentation it seems that if you change the stream open line to:

    stream = p.open(format=p.get_format_from_width(WIDTH),
                    channels=CHANNELS,
                    rate=RATE,
                    input=True,
                    output=True,
                    frames_per_buffer=4096,
                    stream_callback=callback)
    

    that you should get your required number of samples per block. The frames_per_buffer defaults at 1024 so that's probably why you're getting this value in your test.

    Good luck!