Skip to content

sound_level creates a sample buffer every time #53

Closed
@kevinjwalters

Description

@kevinjwalters

The code checks if self._sample has been initialised and then assigns a new buffer to self._samples (note plural!). It looks like a typo which wasn't picked up by linting as _sample is used for playing sounds over tiny speaker.

if self._sample is None:
self._samples = array.array("H", [0] * 160)

This causes a new buffer to be created on each read of the sound_level property. This doesn't leak but it is inefficient and may cause problems for applications with a small amount of (fragmented) remaining memory...


Once this is fixed, a single read of sound_level may be beneficial at the start of a program that's tight on memory or encountering MemoryError: memory allocation failed, allocating 640 bytes exceptions later when sound_level is used repeatedly. This approach aligns with the advice in Adafruit Learn: Memory-saving tips for CircuitPython: Memory: Reducing fragmentation.

Advanced programmers: Allocate a large memory buffer early in the life of your code and reuse the same memory buffer through your program.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions