I am trying to record a long microphone session with pyaudio. However, I get a Memory error after some time. I managed to split it using threading, and record 3 minutes and then process it to a file, but that didn't solve the problem. I also tried to write it directly to a file when recording, but I can't figure out how to append to wav file (using wave module).
This is my code:
CHUNK = 1024
THRESHOLD = 100
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
wf = wave.open("Test.wav", "wb")
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
rec_started = False
num_silent = 0
r = array('h')
while num_silent < 6:
r.extend(array('h', stream.read(CHUNK)))
silent = is_silent(r)
if silent and rec_started:
num_silent += 1
print num_silent
elif not silent and not num_silent:
rec_started = True
data = pack("<" + ("h"*len(r)), *r)
wf.writeframes(data)
wf.close()
My question is: How do I prevent this code from getting a Memory Error after some time?