Python中的线程不需要键盘中断

2024-04-23 14:28:58 发布

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

我是线程新手,我正在写一个简单的程序,可以同时完成两个任务。一个函数将录制任意持续时间的音频,另一个函数只打印一些消息。在录制功能中,使用Ctrl+C键盘中断来停止录制。但是,如果我把这个函数放到python线程中,Ctrl+C就不起作用了,我也不能停止录制。代码如下。任何帮助都将不胜感激。你知道吗

import argparse
import tempfile
import queue
import sys
import threading
import soundfile as sf
import sounddevice as sd

def callback(indata, frames, time, status):
    """
    This function is called for each audio block from the record function.
    """
    if status:
        print(status, file=sys.stderr)
    q.put(indata.copy())

def record(filename='sample_audio.wav'):
    """
    Audio recording.
    Args:
        filename (str): Name of the audio file
    Returns:
        Saves the recorded audio as a wav file
    """
    q = queue.Queue()
    try:
        # Make sure the file is open before recording begins
        with sf.SoundFile(filename, mode='x', samplerate=48000, channels=2, subtype="PCM_16") as file:
            with sd.InputStream(samplerate=48000, channels=2, callback=callback):
                print('START')
                print('#' * 80)
                print('press Ctrl+C to stop the recording')
                print('#' * 80)
                while True:
                    file.write(q.get())
    except OSError:
        print('The file to be recorded already exists.')
        sys.exit(1)
    except KeyboardInterrupt:
        print('The utterance is recorded.')

def sample():
    for i in range(10):
        print('---------------------------------------------------')

def main():
    # Threading
    thread_1 = threading.Thread(target=record, daemon=True)
    thread_2 = threading.Thread(target=sample, daemon=True)
    thread_1.start()
    thread_2.start()
    thread_1.join()
    thread_2.join()

if __name__ == "__main__":
    main()

Tags: the函数importisdefasstatussys