Pyaudio:播放错误:4

时间:2016-03-25 00:30:59

标签: python python-2.7 pyaudio

您好我正在使用pyaudio构建一个实时记录和回放音频的应用程序,为音频信号添加一个低通滤波器。 当我尝试运行此代码时,会出现以下错误:

Pyaudio:播放错误:4

from pyaudio import PyAudio, paContinue, paFloat32
from time import sleep
from numpy import array, random, arange, float32, float64, zeros
import sounddevice as sd

fs            = 44100   # Hz
threshold     = 0.8     # absolute gain
delay         = 40      # samples
signal_length = 1      # second
release_coeff = 0.5555  # release time factor
attack_coeff  = 0.5     # attack time factor
dtype         = float32 # default data type
block_length  = 1024    # samples


class Limiter:
   def __init__(self, attack_coeff, release_coeff, delay, dtype=float32):
    self.delay_index = 0
    self.envelope = 0
    self.gain = 1
    self.delay = delay
    self.delay_line = zeros(delay, dtype=dtype)
    self.release_coeff = release_coeff
    self.attack_coeff = attack_coeff

def limit(self, signal, threshold):
    for i in arange(len(signal)):
        self.delay_line[self.delay_index] = signal[i]
        self.delay_index = (self.delay_index + 1) % self.delay

        # calculate an envelope of the signal
        self.envelope *= self.release_coeff
        self.envelope  = max(abs(signal[i]), self.envelope)

        # have self.gain go towards a desired limiter gain
        if self.envelope > threshold:
            target_gain = (1+threshold-self.envelope)
        else:
            target_gain = 1.0
        self.gain = ( self.gain*self.attack_coeff +
                      target_gain*(1-self.attack_coeff) )

        # limit the delayed signal
        signal[i] = self.delay_line[self.delay_index] * self.gain




    print "Recording Audio"
    signal = sd.rec(signal_length * fs, samplerate=fs, channels=1,    dtype=dtype)
    sd.wait()
    print "Audio recording complete , Play Audio"





original_signal = array(signal, copy=True, dtype=dtype)
limiter = Limiter(attack_coeff, release_coeff, delay, dtype)

def callback(in_data, frame_count, time_info, flag):
    if flag:
        print("Playback Error: %i" % flag)
        played_frames = callback.counter
        callback.counter += frame_count
        limiter.limit(signal[played_frames:callback.counter], threshold)
    return signal[played_frames:callback.counter], paContinue

callback.counter = 0

pa = PyAudio()

stream = pa.open(format = paFloat32,
                 channels = 1,
                 rate = fs,
                 frames_per_buffer = block_length,
                 output = True,
                 stream_callback = callback)

while stream.is_active():
    sleep(0.1)

stream.close()
pa.terminate()

1 个答案:

答案 0 :(得分:1)

你不应该混淆PyAudio和sounddevice

无论如何,如果在回调函数中调用它们,函数sounddevice.rec()sounddevice.wait()将无法正常工作(因为它们在内部使用自己的“流”和自己的回调函数)。