Skip to main content
 首页 » 编程设计

python之pyaudio改变调用回调函数的样本数

2024年11月01日14freeliver54

我想每 4096 个样本对音频进行一次简单的实时处理。但是这段代码每 1024 个样本调用一次回调函数。我只想将 frame_count 更改为 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() 

请您参考如下方法:

我还没有测试过,但是从文档看来,如果您将流打开行更改为:

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) 

您应该获得每个 block 所需的样本数量。 frames_per_buffer 默认为 1024,所以这可能就是您在测试中获得此值的原因。

祝你好运!