record audio until some keypress
I would like to use the following code found elsewhere to record participants' voice using mac. This code allows me to record their voice exactly for three seconds, but I would rather record until they press some key (for example, space). Is there any way to implement this? Thanks
import pyaudio
import wave
import sys
chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 3
WAVE_OUTPUT_FILENAME = "/Users/myname/Desktop/%d_%d.wav" % (self.get('subject_nr'), self.get('count_recorder'))
p = pyaudio.PyAudio()
stream = p.open(format = FORMAT,
channels = CHANNELS,
rate = RATE,
input = True,
frames_per_buffer = chunk)
print "* recording"
all = []
for i in range(0, RATE / chunk * RECORD_SECONDS):
data = stream.read(chunk)
all.append(data)
print "* done recording"
stream.close()
p.terminate()
data = ''.join(all)
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(data)
wf.close()
Comments
After posting this I realised there is already a thread about this. It worked fine for me.
http://forum.cogsci.nl/index.php?p=/discussion/757/solved-record-audio-response-with-variable-time-span/p1