音频流读取功能在多进程中卡住



考虑以下python代码:

class Recorder:
(...)
def __init__(self):
self.p = pyaudio.PyAudio()
self.stream = self.p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
output=True,
frames_per_buffer=chunk)
(...)
def listen(self):
print('Listening beginning')
while True:
input = self.stream.read(chunk)
rms_val = self.rms(input)
if rms_val > Threshold:
self.record()

(...)
import multiprocessing
a = Recorder()
p = multiprocessing.Process(target=a.listen)
####a.listen()
while True:
time.sleep(3)
print("hello world")

代码输入"listen",打印"Listening开始",但当执行"input = self.stream.read(chunk)"时,它会无限循环(音频"chunk")设置为1024)。

当我不使用多处理时不会发生此问题,当我运行"a.listen()"而不是多处理。的过程。我希望代码达到"而True"排队不用等的"听";过程。

如何使它在使用多处理时正常工作?

好的,我让它工作了。

答案很简单。

在这种情况下,我们不应该使用多处理,而应该使用线程:

import threading
a = Recorder()

thread1 = threading.Thread(target = a.listen)
thread1.start()

这样,代码就可以正常工作了。

最新更新