linux – Rpi Python Script Keeps Running After Stopped

I have a Raspberry Pi, with a pyaudio script. I am recording and when I keyboardInterrupt (normally it would be another way of closing, but I keyboardInterrupt for demonstrative purposes) Anyway, when I keyboardInterrupt, it keeps exporting. Any ideas on how to stop it from doing that?

My code:

import pyaudio
import time
import wave
import RPi.GPIO as GPIO
from datetime import datetime

rg = False #rg is short for recording if rg is false then I'm not recording

# Configuration
BUTTON_PIN = 27  # GPIO pin number for the button
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 0  # Not used directly in this case

# Initialize PyAudio
audio = pyaudio.PyAudio()

# GPIO setup
GPIO.setmode(GPIO.BCM)
#GPIO.setwarnings(False)
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(BUTTON_PIN_TWO, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(10, GPIO.OUT)  # green
GPIO.setup(9, GPIO.OUT)  # yellow
GPIO.setup(11, GPIO.OUT)  # red

def record_audio(filename):
    global stream, frames, rg
    stream = audio.open(format=FORMAT, channels=CHANNELS,
                        rate=RATE, input=True, frames_per_buffer=CHUNK)
    GPIO.output(11, GPIO.HIGH)
    print("Recording started")

    rg = True #i'm recording

    frames = []
    while GPIO.input(BUTTON_PIN) == GPIO.LOW: #if button is being held down, record
        data = stream.read(CHUNK)
        frames.append(data)

    close_recording(stream)
    write_file(filename, frames)

def close_recording(recording):
    global rg
    recording.stop_stream()
    recording.close()
    GPIO.output(11, GPIO.LOW)
    print("Recording stopped")
    rg = False #i'm not

def write_file(filename, frames):
    global rg
    # Save to WAV file
    wf = wave.open(filename, 'wb')
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(audio.get_sample_size(FORMAT))
    wf.setframerate(RATE)
    wf.writeframes(b''.join(frames))
    wf.close()
    GPIO.output(9, GPIO.HIGH)
    time.sleep(1)
    GPIO.output(9, GPIO.LOW)
    print(f"Audio saved to {wav_filename}")

def main():
    global wav_filename, rg
    try:
       #light sequence to show that device turned on
       GPIO.output(10, GPIO.HIGH)
       time.sleep(0.3)
       GPIO.output(10, GPIO.LOW)
       GPIO.output(9, GPIO.HIGH)
       time.sleep(0.3)
       GPIO.output(9, GPIO.LOW)
       GPIO.output(11, GPIO.HIGH)
       time.sleep(0.3)
       GPIO.output(11, GPIO.LOW)
       GPIO.output(9, GPIO.HIGH)
       time.sleep(0.3)
       GPIO.output(9, GPIO.LOW)
       GPIO.output(10, GPIO.HIGH)
       time.sleep(0.3)
       GPIO.output(10, GPIO.LOW)
       GPIO.output(10, GPIO.HIGH)
       while True:
            if GPIO.input(BUTTON_PIN) == GPIO.LOW: #when button is held down record
                rg = True
                # Button pressed: Record audio
                timestamp = datetime.now().strftime("%m-%d-%Y_%H-%M-%S")
                wav_filename = f"/home/pi/Desktop/Audio_Files/{timestamp}.wav"

                record_audio(wav_filename)

                # Wait a bit to avoid multiple recordings from a single press
                time.sleep(1)
            else:
                rg = False
                time.sleep(0.1)  # Polling delay

    except KeyboardInterrupt:
        print("Exiting...")

    except:
        #flashing light to show error
        time.sleep(1)
        GPIO.output(9, GPIO.LOW)
        GPIO.output(11, GPIO.LOW)
        t_end = time.time() + 15 * 1
        while time.time() < t_end:
            time.sleep(0.3)
            GPIO.output(9, GPIO.HIGH)
            time.sleep(0.3)
            GPIO.output(9, GPIO.LOW)
            time.sleep(0.3)

    finally:
        if(rg == True):
           #rg = False
           close_recording(stream)
           write_file(wav_filename, frames)
           audio.terminate()
           GPIO.output(11, GPIO.LOW)
           GPIO.output(10, GPIO.LOW)
           GPIO.output(9, GPIO.LOW)
           GPIO.cleanup()
        else:
           time.sleep(0.1)
           audio.terminate()
           GPIO.output(11, GPIO.LOW)
           GPIO.output(10, GPIO.LOW)
           GPIO.output(9, GPIO.LOW)
           GPIO.cleanup()

if __name__ == "__main__":
    main()

Any help is greatly appreciated, I’ve been stuck for 2 months.

Read more here: Source link