15
15
#define AUDIO_BUFFER_SIZE_BYTES (PICOVOICE_FRAME_SIZE * sizeof(int16_t))
16
16
17
17
static int32_t _dma_buffer [PICOVOICE_FRAME_SIZE * 2 ];
18
-
18
+ static volatile uint8_t _audio_active = 0 ;
19
19
// ---------------------------- Azure RTOS Config --------------------------- //
20
20
#define NUM_AUDIO_BUFFERS (16)
21
21
@@ -68,6 +68,8 @@ void AUDIO_Start(void)
68
68
{
69
69
log_info ("AUDIO_Start" );
70
70
71
+ _audio_active = 1 ;
72
+
71
73
HAL_SAI_Receive_DMA (& hsai_BlockB1 , (uint8_t * )_dma_buffer , PICOVOICE_FRAME_SIZE * 2 );
72
74
}
73
75
@@ -76,13 +78,24 @@ void AUDIO_Stop(void)
76
78
log_info ("Stopping audio capture" );
77
79
78
80
// Stop DMA
81
+ _audio_active = 0 ;
79
82
HAL_SAI_DMAStop (& hsai_BlockB1 );
80
83
81
- // Flush queue
82
- UINT status = tx_queue_flush (& _audio_data_queue );
83
- if (status != TX_SUCCESS )
84
+ // Wait 1ms for remaining audio
85
+ tx_thread_sleep ((1 * TX_TIMER_TICKS_PER_SECOND ) / 1000 );
86
+
87
+ // Drain queue, release all pending buffers
88
+ int16_t * buffer ;
89
+ UINT status ;
90
+
91
+ while (tx_queue_receive (& _audio_data_queue , & buffer , TX_NO_WAIT ) == TX_SUCCESS )
84
92
{
85
- log_fatal ("Failed to flush audio data queue: %d" , status );
93
+ // Release the buffer back to the byte pool
94
+ status = tx_block_release (buffer );
95
+ if (status != TX_SUCCESS )
96
+ {
97
+ log_error ("Failed to release audio buffer back to byte pool: %d" , status );
98
+ }
86
99
}
87
100
}
88
101
@@ -111,6 +124,12 @@ static void processData(const int32_t *dma_src, int16_t *dest)
111
124
112
125
void dmaCallbackHandler (int32_t * dma_buffer )
113
126
{
127
+ if (!_audio_active )
128
+ {
129
+ log_debug ("Audio inactive, dropping frame" );
130
+ return ;
131
+ }
132
+
114
133
// Allocate buff from byte pool
115
134
int16_t * buffer = NULL ;
116
135
UINT status = tx_block_allocate (& _audio_block_pool , (VOID * * )& buffer , TX_NO_WAIT );
0 commit comments