import pyaudio
import numpy as np
import wave
import os

CHUNK_SIZE = 1024  # number of audio samples per frame
FORMAT = pyaudio.paInt16  # audio format (16-bit integers)
CHANNELS = 1  # mono audio
RATE = 44100  # sample rate (Hz)

dir = os.path.join(os.getcwd(), 'preuve/voices/')

def detect_sound(threshold=0.05, duration=5, filename='recording.wav'):
    p = pyaudio.PyAudio()
    stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK_SIZE)

    frames = []
    recorded_frames = 0

    while True:
        data = np.frombuffer(stream.read(CHUNK_SIZE), dtype=np.int16) / 32768.0
        rms = np.sqrt(np.mean(np.square(data)))
        if rms > threshold:
            print("Sound detected!")
            recorded_frames = int(RATE / CHUNK_SIZE * duration)
            for i in range(recorded_frames):
                frames.append(stream.read(CHUNK_SIZE))
            break

    stream.stop_stream()
    stream.close()
    p.terminate()

    wf = wave.open(filename, 'wb')
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(p.get_sample_size(FORMAT))
    wf.setframerate(RATE)
    wf.writeframes(b''.join(frames))
    wf.close()

    print(f"Recording saved as {filename}")
c=0
while True:
    filename=dir+'myrecording'+str(c)+'.wav'
    detect_sound(threshold=0.05, duration=10, filename=filename)
    c+=1
