R
R
r1mple2021-10-12 22:34:28
Python
r1mple, 2021-10-12 22:34:28

How to get rid of keyboard in pyaudio?

stream = self.p.open(format=self.FORMAT,
                            channels=self.CHANNELS,
                            rate=self.RATE,
                            input_device_index=2,
                            frames_per_buffer=self.CHUNK,
                            input=True)
                            
print('------- Recording... -------')

while not keyboard.is_pressed('s'):
       data = stream.read(self.CHUNK)
       self.frames.append(data)
        
print('------- Finished recording. -------')

stream.stop_stream()
stream.close()
self.p.terminate()

Here I have such a code, how can I get rid of the keyboard here? So that the recording does not stop on the button, but there is a function to stop the recording.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
r1mple, 2021-10-13
@r1mple

in general, I wrote a solution for anyone who needs it.

def start(self):   
        print('------- Recording... -------')

        while self.recordFlag:
            data = self.stream.read(self.CHUNK)
            self.frames.append(data)
            self.frame = np.array([data])

        print('------- Finished recording. -------')  
    
    def stop_and_save(self):
        print('Do you want to stop recording? (y/n)', end=' ')
        ans = input()
        if ans == 'y': 
            self.recordFlag = False
            self.stream.stop_stream()
            self.stream.close()
            self.p.terminate()  
            wf = wave.open(self.WAVE_OUTPUT_FILENAME, 'wb')
            wf.setnchannels(self.CHANNELS)
            wf.setsampwidth(self.p.get_sample_size(self.FORMAT))
            wf.setframerate(self.RATE)
            wf.writeframes(b''.join(self.frames))
            wf.close()

audioStartThread = threading.Thread(target=ac.start)
audioStopThread = threading.Thread(target=ac.stop_and_save)
audioStartThread.start() 
audioStopThread.start()

In general, according to the mind, it would be possible to implement this not through streams, but through asynchrony.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question