如何在 Pyaudio 回调模式下处理 in_data?

问题描述:

我正在用 python 做一个关于信号处理的项目.到目前为止,我在非阻塞模式方面取得了一些成功,但它给输出带来了相当大的延迟和限幅.

I'm doing a project on Signal Processing in python. So far I've had a little succes with the nonblocking mode, but it gave a considerable amount of delay and clipping to the output.

我想使用 Pyaudio 和 Scipy.Signal 实现一个简单的实时音频过滤器,但是在 pyaudio 示例中提供的回调函数中,当我想读取 in_data 时,我无法处理它.尝试以各种方式转换它,但没有成功.

I want to implement a simple real-time audio filter using Pyaudio and Scipy.Signal, but in the callback function provided in the pyaudio example when I want to read the in_data I can't process it. Tried converting it in various ways but with no success.

这是我想要实现的代码(尽快从麦克风、过滤器和输出中读取数据):

Here's a code I want to achieve(read data from mic, filter, and output ASAP):

import pyaudio
import time
import numpy as np
import scipy.signal as signal
WIDTH = 2
CHANNELS = 2
RATE = 44100

p = pyaudio.PyAudio()
b,a=signal.iirdesign(0.03,0.07,5,40)
fulldata = np.array([])

def callback(in_data, frame_count, time_info, status):
    data=signal.lfilter(b,a,in_data)
    return (data, pyaudio.paContinue)

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

stream.start_stream()

while stream.is_active():
    time.sleep(5)
    stream.stop_stream()
stream.close()

p.terminate()

这样做的正确方法是什么?

What is the right way to do this?

在此期间找到了我的问题的答案,回调如下:

Found the answer to my question in the meantime, the callback looks like this:

def callback(in_data, frame_count, time_info, flag):
    global b,a,fulldata #global variables for filter coefficients and array
    audio_data = np.fromstring(in_data, dtype=np.float32)
    #do whatever with data, in my case I want to hear my data filtered in realtime
    audio_data = signal.filtfilt(b,a,audio_data,padlen=200).astype(np.float32).tostring()
    fulldata = np.append(fulldata,audio_data) #saves filtered data in an array
    return (audio_data, pyaudio.paContinue)