@@ -27,7 +27,8 @@ class RecordStream:
2727 DEFAULT_MAX_DURATION_MS = 60000 # 60 seconds max
2828 DEFAULT_FILESIZE = 1024 * 1024 * 1024 # 1GB data size because it can't be quickly set after recording
2929
30- def __init__ (self , file_path , duration_ms , sample_rate , i2s_pins , on_complete ):
30+ def __init__ (self , file_path , duration_ms , sample_rate , i2s_pins , on_complete ,
31+ on_open = None , on_close = None ):
3132 """
3233 Initialize recording stream.
3334
@@ -37,12 +38,16 @@ def __init__(self, file_path, duration_ms, sample_rate, i2s_pins, on_complete):
3738 sample_rate: Sample rate in Hz
3839 i2s_pins: Dict with 'sck', 'ws', 'sd_in' pin numbers
3940 on_complete: Callback function(message) when recording finishes
41+ on_open: Optional callable invoked after MCLK starts, before I2S init
42+ on_close: Optional callable invoked before I2S deinit
4043 """
4144 self .file_path = file_path
4245 self .duration_ms = duration_ms if duration_ms else self .DEFAULT_MAX_DURATION_MS
4346 self .sample_rate = sample_rate if sample_rate else self .DEFAULT_SAMPLE_RATE
4447 self .i2s_pins = i2s_pins
4548 self .on_complete = on_complete
49+ self .on_open = on_open
50+ self .on_close = on_close
4651 self ._keep_running = True
4752 self ._is_recording = False
4853 self ._i2s = None
@@ -152,6 +157,13 @@ def record(self):
152157 except Exception as e :
153158 print (f"RecordStream: MCLK PWM init failed: { e } " )
154159
160+ # Notify codec to prepare for recording (e.g. mute DAC, configure ADC)
161+ if self .on_open :
162+ try :
163+ self .on_open ()
164+ except Exception as e :
165+ print (f"RecordStream: on_open failed: { e } " )
166+
155167 # Use sck_in if available (separate clock for mic), otherwise fall back to sck
156168 sck_pin = self .i2s_pins .get ('sck_in' , self .i2s_pins .get ('sck' ))
157169 print (f"RecordStream: Initializing I2S RX with sck={ sck_pin } , ws={ self .i2s_pins ['ws' ]} , sd={ self .i2s_pins ['sd_in' ]} " )
@@ -260,6 +272,11 @@ def record(self):
260272
261273 finally :
262274 self ._is_recording = False
275+ if self .on_close :
276+ try :
277+ self .on_close ()
278+ except Exception as e :
279+ print (f"RecordStream: on_close failed: { e } " )
263280 if self ._i2s :
264281 self ._i2s .deinit ()
265282 self ._i2s = None
0 commit comments