我正在编写一个音频处理脚本,该脚本侦听音频并在其上运行语音识别。 我正在使用PyAudio回调函数来捕获音频帧,并在音频级别高于特定阈值时触发记录/停止。
问题在于,每当语音剪辑在剪辑上运行时(在主循环中),回调似乎就不会运行。这很令人困惑,因为我相信回调在单独的线程中运行。
如果将行speech = get_text(samples)
替换为time.sleep(10)
,则在主循环阻塞的同时继续调用回调。
当我执行诸如计算math.sin
的其他操作达10秒钟时,回调也可以正常工作。
我的问题是,什么可能导致回调在主线程中运行任意代码而time.sleep
允许的情况下停止在其自己的线程中运行?
def audio_callback(self, in_data, frame_count, time_info, flag):
""" This gets called whenever the audio stream receives new data. """
rms = audioop.rms(in_data, 2)
if rms > AUDIO_TRIGGER_LEVEL:
logger.debug("Recording")
self.recording = True
self.recording_quiet_count = 0
else:
if self.recording:
self.recording_quiet_count += 1
if self.recording_quiet_count > QUIET_CHUNKS_BEFORE_STOP:
logger.debug("Stopping recording")
self.recording = False
self.recording_quiet_count = 0
self.data_to_process = True
if self.recording:
self.recorded_frames.append(in_data)
return ('', pyaudio.paContinue)
def run(self):
while True:
time.sleep(0.05)
if self.data_to_process:
logger.debug("Processing recording")
tot_frames = CHUNK_SIZE * len(self.recorded_frames)
frames = b''.join(self.recorded_frames)
self.recorded_frames = []
self.data_to_process = False
samples = struct.unpack_from('<%dh' % tot_frames, frames)
# This is the part causing issues
speech = get_text(samples)
# time.sleep(10)