i wanted to record audio using max9814 and raspberry pi pico with micropython/circuitpython but when i recorded the data, some parts of it lose because it's trying to read the data and write the data into a .wav file and it can not hadle it simultaneously.
the circuit is like below:
| RPI PICO | MAX9814 |
|---|---|
| GP26 | OUT |
| 3v3 | VDD |
| GND | GND |
my code is below:
import board
import analogio
import time
import adafruit_wave
import struct
import storage
# storage.remount("/", readonly=False)
adc = analogio.AnalogIn(board.A0)
conversion_factor = 3.3/4096
buffer = []
f = adafruit_wave.open("audio.wav", "w")
f.setnchannels(1)
f.setsampwidth(2)
f.setframerate(8000)
def save(data):
global f
f.writeframes(bytearray(data))
print("done")
try:
while True:
sample = adc.value * conversion_factor
frame = bytearray(struct.pack('>H', int(sample)))
buffer.extend(frame)
if len(buffer) > 16000:
save(buffer)
buffer = []
print("clear buffer")
except KeyboardInterrupt:
print("closing")
f.close()
How can i handle it?
Alright, so here's the thing: your code's trying to do too much at once and the Pico can't keep up. The trick is to split the recording and saving parts so they don't step on each other's toes. You'll use threading to handle this. Micropython on the Pico doesn't support
threadinglike full Python, but CircuitPython does something similar withasyncio. Here's a quick fix usingasyncioto manage both tasks without them interfering with each other:First, you gotta make sure your CircuitPython firmware is up to date because
asynciois kinda recent.Then, tweak your setup like this:
This code sets up async functions for recording audio to a buffer and saving that buffer to a file once it's full. It then runs both tasks concurrently, so one can gather data while the other writes to the disk, preventing the loss you're experiencing. The
asyncio.sleep(0)calls yield execution between tasks, allowing both to proceed without blocking each other.