Skip to content

Commit 5c1a9de

Browse files
committed
Drop temporary buffers and CFFI objects when stream is finished
Closes #58. Closes #158.
1 parent 221fd8f commit 5c1a9de

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

sounddevice.py

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -268,7 +268,7 @@ def rec(frames=None, samplerate=None, channels=None, dtype=None,
268268
269269
"""
270270
ctx = _CallbackContext()
271-
ctx.frames = ctx.check_out(out, frames, channels, dtype, mapping)
271+
out, ctx.frames = ctx.check_out(out, frames, channels, dtype, mapping)
272272

273273
def callback(indata, frames, time, status):
274274
assert len(indata) == frames
@@ -278,7 +278,7 @@ def callback(indata, frames, time, status):
278278

279279
ctx.start_stream(InputStream, samplerate, ctx.input_channels,
280280
ctx.input_dtype, callback, blocking, **kwargs)
281-
return ctx.out
281+
return out
282282

283283

284284
def playrec(data, samplerate=None, channels=None, dtype=None,
@@ -355,8 +355,8 @@ def playrec(data, samplerate=None, channels=None, dtype=None,
355355
output_frames = ctx.check_data(data, output_mapping, kwargs.get('device'))
356356
if dtype is None:
357357
dtype = ctx.data.dtype # ignore module defaults
358-
input_frames = ctx.check_out(out, output_frames, channels, dtype,
359-
input_mapping)
358+
out, input_frames = ctx.check_out(out, output_frames, channels, dtype,
359+
input_mapping)
360360
if input_frames != output_frames:
361361
raise ValueError('len(data) != len(out)')
362362
ctx.frames = input_frames
@@ -374,7 +374,7 @@ def callback(indata, outdata, frames, time, status):
374374
callback, blocking,
375375
prime_output_buffers_using_stream_callback=False,
376376
**kwargs)
377-
return ctx.out
377+
return out
378378

379379

380380
def wait(ignore_errors=True):
@@ -2402,6 +2402,7 @@ class _CallbackContext(object):
24022402

24032403
blocksize = None
24042404
data = None
2405+
out = None
24052406
frame = 0
24062407
input_channels = output_channels = None
24072408
input_dtype = output_dtype = None
@@ -2483,7 +2484,7 @@ def check_out(self, out, frames, channels, dtype, mapping):
24832484
self.input_channels = channels
24842485
self.input_dtype = dtype
24852486
self.input_mapping = mapping
2486-
return frames
2487+
return out, frames
24872488

24882489
def callback_enter(self, status, data):
24892490
"""Check status and blocksize."""
@@ -2521,6 +2522,12 @@ def callback_exit(self):
25212522

25222523
def finished_callback(self):
25232524
self.event.set()
2525+
# Drop temporary audio buffers to free memory
2526+
self.data = None
2527+
self.out = None
2528+
# Drop CFFI objects to avoid reference cycles
2529+
self.stream._callback = None
2530+
self.stream._finished_callback = None
25242531

25252532
def start_stream(self, StreamClass, samplerate, channels, dtype, callback,
25262533
blocking, **kwargs):

0 commit comments

Comments
 (0)