The Code:
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, 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 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): global rg recording.stop_stream() recording.close() GPIO.output(11, GPIO.LOW) print("Recording stopped") rg = Falsedef 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: 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): #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()
Statistics: Posted by Henrik Gill — Fri Oct 11, 2024 9:48 pm