I faced a similar issue while working on a project. Here is my simplified approach using just keyboard
module.
We can divide the problem in 3 parts:
- Waiting for Key Press
- Record while Key is pressed (held)
- Stop recording upon Key release
The first part is tricky, there are multiple solutions using listeners
, while True
loops, input
and raw_input
implementations. I was struggling with configuring these implementations and went ahead with keyboard.wait(<your key choice>)
. This blocks the program till the key of choice is pressed. If you do not pass in any argument, it waits for any key press.
The second part is resolved by a while
loop which executes till the key is pressed. After the first two are resolved, the third part falls in place as the is_pressed
has a mechanism which detects if the key is held down/pressed. This is what is pointed out by @Sajuuk in his solution.
Here is an implementation of the code:
import pyaudio
import keyboard
def audioRecord(object):
chunk = 1024 # Record in chunks of 1024 samples
sample_format = pyaudio.paInt16 # 16 bits per sample
channels = 2
fs = 44100 # Record at 44100 samples per second
p = pyaudio.PyAudio() # Create an interface to PortAudio
# Open the stream
stream = p.open(format=sample_format,
channels=channels,
rate=fs,
frames_per_buffer=chunk,
input=True)
frames = [] # Initialize array to store frames
# ----- Solution starts here -----
print('Hold Space to record')
keyboard.wait('space') # Waits for key press
if keyboard.is_pressed('space'):
print('Recording...')
while keyboard.is_pressed('space'): # Records till key is pressed/held down
data = stream.read(chunk)
frames.append(data)
# Stop and close the stream
stream.stop_stream()
stream.close()
# Terminate the PortAudio interface
p.terminate()
print('Finished recording')
You can now process these frames as per your requirement. Save it in a file or process the frames directly. Just couple of recommendations, add a timeout
for the keyboard.wait()
to avoid the program to be blocked indefinitely.
Hope this answer helps, cheers :)