I’m working on playing audio with the Imp in an environment where RAM has become very scarce. I’m allocating space for blobs to use as audio buffers at boot time, and trying to reuse the same blobs whenever playing audio. The hope here is to avoid freeing and reallocating the space for the blobs, which could see me run into problems with memory fragmentation.
The problem is that at the end of playing a sound I need to load a blob into the DAC that is shorter than my audio buffers. There are a number of ways I could do this, but I need one that doesn’t use any more or less memory than is already used, i.e. I don’t want to make my buffer blob smaller to match the smaller data, to deallocate the buffer blob, or to allocate another seperate blob either.
I know that by using
blob.resize() to make a small blob larger you can create a blob that has allocated space greater than it’s length/size. I want the same thing, but in a backwards kind of way. So I have a buffer blob (let’s say 4kb). I want to leave the blob where it is in memory, and maintain 4kb allocated space, but load some audio data into it (let’s say 2kb, using a
.readintoblob() type method), and have the
blob.len() shrink to match the size of the audio (2kb). There’s no blob method that does what I want to do, which is shrink the length of a blob without changing the allocation. Would either of the following approaches work?
buffer.resize(0); // Shrink the buffer so len == alloc == 0 buffer.resize(4096); // Immediately grow the buffer so alloc == 4096 but len == 0 audio.readintoblob(buffer, 2048); // Copy the data so len == 2048 but alloc still == 4096
buffer = null; // Free the buffer's memory buffer = buffer(4096); // Allocate a new (empty) buffer, hopefully into the same space, so len == 0 and alloc == 4096 audio.readintoblob(buffer, 2048); // Copy the data so len == 2048 but alloc still == 4096
Or any other ideas?