I have a Qt timer that I want to count down while I record (using the sound device package), I'll attach what I have below (I know it is very far off from anything correct). I've been reading up on multiprocessing and threads, and I think the timeout allows for other functions to be ran, but it seems the record function holds while its writing the file, so I am a bit stumped. Any advice helps, thanks!
class CountDown(QWidget):
def __init__(self, name, index):
super().__init__()
self.initUI(name, index)
def initUI(self, name, index):
self.setWindowTitle("Timer for "+name)
layout = QVBoxLayout()
self.setLayout(layout)
self.time_label = QLabel(self)
layout.addWidget(self.time_label)
self.setFixedWidth(500)
self.setFixedHeight(500)
# Create a QTimer that updates the time label every second
timer = QTimer(self)
self.current_time = 11
timer.timeout.connect(lambda: self.update_time())
timer.start(1000) # Update every 1000 milliseconds (1 second)
print("START RECORDING" + name)
self.record(index, name)
self.show()
#need to update time and record simultaneously
def update_time(self):
# Get the current time and set it on the label
if(self.current_time==0):
self.close()
self.current_time-=1
print(self.current_time)
self.time_label.setText(f"Current Time: {self.current_time}")
#Takes in name selected from GUI and finds its index to use for audio device-> records for 1 second
def record(self, index, name):
#1 Microphone (USB Lavalier Microp, MME (2 in, 0 out)
# Sample rate:
fs = 44100
# Duration of recording:
seconds = 5
myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=1, device=index)
# Wait until recording is finished:
sd.wait()
print("STOPPED RECORDING" + name)
# Save as WAV file:
write(name+".wav", fs, myrecording)
return name+".wav"
I would reach for
threadinghere. Not all of Qt is thread-safe, but if your recording thread does not directly interact with the GUI, There's almost no work necessary:It is possible to emit signals from a thread, so you can create a slot (a callback) which can be triggered by the thread. If you start trying to do stuff like
label.setText()from a thread that's where you get into trouble.^note: code is untested.. read for changes and understanding.