阻止操作期间未运行PyAudio回调

2024-05-29 04:32:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个音频处理脚本,它可以监听音频并在上面运行语音识别。 我使用PyAudio回调函数来捕获音频帧,并在音频级别高于某个阈值时触发录制/停止。你知道吗

问题是,每当语音识别在一个剪辑(在主循环中)上运行时,回调似乎不会运行。这让人困惑,因为我认为回调运行在一个单独的线程中。 如果我用time.sleep(10)替换speech = get_text(samples)行,那么在主循环阻塞时,回调将继续被调用。 当我在10秒钟内执行computemath.sin之类的操作时,回调也可以继续正常工作。你知道吗

我的问题是,当在主线程中运行任意代码,而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)

Tags: inselfdataframesiftimecountsleep

热门问题