0

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?

J-Star
  • 96
  • 3
  • 8
  • 1
    I don't know how to fix your code, but you can have a look at my [rec_unlimited.py](https://github.com/spatialaudio/python-sounddevice/blob/master/examples/rec_unlimited.py) example using the [sounddevice](http://python-sounddevice.readthedocs.io/) module. – Matthias Dec 07 '16 at 09:37
  • I will take a look at that, it looks promising, thanks! – J-Star Dec 08 '16 at 11:27
  • What is "some time"? It makes sense that as the sound is saved it is bounded by the amount of memory available in the system. You could try to save fragments on your hard drive iso keeping everything in your memory. – Zafi Dec 08 '16 at 11:46
  • After about 10 minutes it raises the error. I agree with you that I should save fragments. However, I tried saving it every 3 minutes to my hard-disk, but with no result. It still raises a Memory Error. – J-Star Dec 08 '16 at 13:32
  • @Matthias I tried using your example, but I sill get the Memory Error. I will try to see if it's in another part of my code. Thanks a bunch! – J-Star Dec 14 '16 at 12:54

0 Answers0