How to end while loop by a button

Summary

How to stop while loop with a click of button

Steps to reproduce

Code snippet:

with col1:
    if st.button('Record Audio'):
        st.write('Recording starts')
        recorder.start()
        while Record_stop == 0:
            frame = recorder.read()
            audio.extend(frame)
            print('Recording')
            
with col2:
    if st.button('Stop Recording'):
        Record_stop = 1
        recorder.stop()
        st.write('Recording stopped')
        Record_stop = 0 

Expected behavior:
When i click on “Stop Recording” Button, I would want to stop the while loop which is running when I click on “Record Audio” button.

Actual behavior:

Right now the “Stop Recording” button is not responding as i want.

I might be missing some basic python syntax or rules here, But i am not sure for now.
TIA

Hi @RohitM

You could look into using Session State and on click callbacks (see 1 and 2) with the buttons.

A while back, I made a real-time transcription app tutorial video with the corresponding code showing this in action.

Best regards,
Chanin