Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 2461

General discussion • Python Script keeps Exporting after Finally Statement

$
0
0
My python script is supposed to if recording save and export the file if interrupted. It does do that, but after, just keeps exporting and making more and more recordings.
My code is below:

Code:

import pyaudioimport timeimport waveimport RPi.GPIO as GPIOfrom datetime import datetimerg = False# ConfigurationBUTTON_PIN = 27  # GPIO pin number for the buttonBUTTON_PIN_TWO = 17 # GPIO pin number for the second buttonCHUNK = 1024FORMAT = pyaudio.paInt16CHANNELS = 1RATE = 44100RECORD_SECONDS = 0  # Not used directly in this case# Initialize PyAudioaudio = pyaudio.PyAudio()# GPIO setupGPIO.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)  # greenGPIO.setup(9, GPIO.OUT)  # yellowGPIO.setup(11, GPIO.OUT)  # reddef record_audio(filename):    global stream, frames    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    frames = []    while GPIO.input(BUTTON_PIN) == GPIO.LOW:        data = stream.read(CHUNK)        frames.append(data)    close_recording(stream)    write_file(filename, frames)def close_recording(recording):   try:       recording.stop_stream()       recording.close()       GPIO.output(11, GPIO.LOW)       print("Recording stopped")       rg = False   except: passdef write_file(filename, frames):   try:       # 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}")   except: passdef main():    global wav_filename    try:       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:                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:        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):           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 way to make it stop exporting recordings over and over and only export once if I stop the script while I'm recording?

Statistics: Posted by Henrik Gill — Sun Oct 06, 2024 5:50 pm



Viewing all articles
Browse latest Browse all 2461

Trending Articles