I am newbie in Threading and I am writing a simple program which can do two tasks simultaneously. One function will record audio for arbitrary duration and the other function will just print some messages. In the record function, the Ctrl+C keyboard interrupt is used to stop the recording. But, if I put this function into a python thread, the Ctrl+C is not working and I am not able to stop the recording. The code is as follows. Any help is kindly appreciated.
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()