How to handle in_data in Pyaudio callback mode?

I am doing a signal processing project in python. So far, I have had little success in non-blocking mode, but this has given significant delay and clipping at the output.

I want to implement a simple real-time sound filter using Pyaudio and Scipy.Signal, but in the callback function presented in the pyaudio example, when I want to read in_data, I cannot process it. I tried to convert it in different ways, but without success.

Here is the code I want to achieve (read data from microphone, filter and ASAP output):

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?

+4
source share
1 answer

, :

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)
+5

Source: https://habr.com/ru/post/1529451/


All Articles