python-sounddevice icon indicating copy to clipboard operation
python-sounddevice copied to clipboard

Memory issue with sd.rec

Open LutzFassl opened this issue 5 years ago • 3 comments

Hello! Thank you for the sounddevice library. It's very nice & handy. However I have the following issue:

I run a very simple program that continuously records 10minute arrays, 1 channel, 44100 Hz. Those 10 minute recordings should only use 101mb per numpy array. The memory usage is increasing over time until python 32bit runs out of memory and crashes. (after ~6 hours) After 1h it's already somewhere in the range of 600-1200mb memory usage, while the program starts at 153mb.

Raspberry Pi 4 8GB: Raspian 4.19 32bit Python 3.7.3 32bit Sounddevice 0.3.15 Numpy 1.19.0

import sounddevice as sd
import soundfile as sf
from datetime import datetime

seconds = 600  # Duration of recording (s)
fs = 44100  # Sample rate

while True:
	savestring = datetime.now().strftime("%Y-%m-%d %H-%M-%S") + ".flac"
	rec = sd.rec(int(seconds * fs), samplerate=fs, channels=1)
	sd.wait()  # Wait until recording is finished
	#sf.write(savestring, rec, fs) #save --> is commented out because memory problem is independent from that code line

Error message:

Traceback (most recent call last):
  File "my_recording.py", line 28, in loop
    rec = sd.rec(int(seconds * fs), samplerate=fs, channels=1)
  File "/home/pi/venv_cv/lib/python3.7/site-packages/sounddevice.py", line 271, in rec
    ctx.frames = ctx.check_out(out, frames, channels, dtype, mapping)
  File "/home/pi/venv_cv/lib/python3.7/site-packages/sounddevice.py", line 2437, in check_out
    out = np.empty((frames, channels), dtype, order='C')
MemoryError: Unable to allocate 101. MiB for an array with shape (26460000, 1) and data type float32

Is there a fix or a workaround?

LutzFassl avatar Jul 06 '20 18:07 LutzFassl

I've very recently fixed some memory issues in #250, does that also happen to fix your issue?

mgeier avatar Jul 06 '20 18:07 mgeier

You mean replace my sounddevice.py with the changed version from #250 ? I will give it a try

EDIT: Yes that fixed it. Thanks a lot :-) looking forward to see this change in a future release

LutzFassl avatar Jul 06 '20 19:07 LutzFassl

Thanks for testing!

You mean replace my sounddevice.py with the changed version from #250 ?

Yes, you can do this.

Or you can check out the PR with Git and make a development installation as described in https://python-sounddevice.readthedocs.io/en/latest/CONTRIBUTING.html#development-installation

If you need help with that, let me know!

looking forward to see this change in a future release

I want to merge a few open PRs first, but I'll make a new release soon.

mgeier avatar Jul 15 '20 15:07 mgeier

I think this has been resolved.

mgeier avatar Oct 10 '22 18:10 mgeier